Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Last value of array when object available

I am trying to find the last value of GDPAnn from the array Annual. The code below works fine. But if GDPAnn is not available in the last value, it returns undefined. For example, I want value 10251000 of GDPAnn from array Annual2.

var Annual = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1,"GDPAnn":10581900}]

x = Annual.map((o) => o.GDPAnn).pop();
console.log(x);

var Annual2 = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1}]

y = Annual2.map((o) => o.GDPAnn).pop();
console.log(y);

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Please see comment in code below - use .filter()

var Annual = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1,"GDPAnn":10581900}]

x = Annual.map((o) => o.GDPAnn).pop();
console.log(x);

var Annual2 = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1}]

// Adding filter here to only include items with the GDPAnn key
y = Annual2.filter((o) => o.GDPAnn).map((o) => o.GDPAnn).pop();
console.log(y);

about 4 years ago · Juan Pablo Isaza Report

0

This could be a simple workaround

var Annual = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1,"GDPAnn":10581900}]

x = Annual.map((o) => o.GDPAnn).pop();
console.log(x);

var Annual2 = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1}]

y = Annual2.filter(o=> o.GDPAnn).map((o) => o.GDPAnn).pop();
console.log(y);

about 4 years ago · Juan Pablo Isaza Report

0

let y = Annual2.reduce((prev, curr) => curr.GDPAnn ? curr : prev).GDPAnn
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!