Ujjawal Bhandari
Ujjawal Bhandari

Reputation: 1372

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

Upvotes: 1

Views: 44

Answers (3)

Bane2000
Bane2000

Reputation: 187

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

Upvotes: 0

Peterrabbit
Peterrabbit

Reputation: 2247

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

Upvotes: 1

StudioTime
StudioTime

Reputation: 23979

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

Upvotes: 2

Related Questions