1

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);

3
  • Filter the array to only include items with a key GDPAnn before running your .map() Commented Mar 21, 2022 at 10:07
  • Thanks. Can you guide me as I am new to JS? Commented Mar 21, 2022 at 10:08
  • Added as an answer Commented Mar 21, 2022 at 10:11

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0
let y = Annual2.reduce((prev, curr) => curr.GDPAnn ? curr : prev).GDPAnn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.