Home > Blockchain >  Last value of array when object available
Last value of array when object available

Time:03-21

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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