Designer
Designer

Reputation: 35

How to sum of array object in Javascipt

i have this array:

    var res =
[
  { '5': 0 },  { '23': 0 },
  { '74': 0 }, { '45': 0 },
  { '10': 0 }, { '46': 1 },
  { '33': 0 }, { '18': 0 },
  { '67': 1 }, { '28': 0 },
  { '68': 0 }, { '56': 0 },
  { '78': 0 }, { '71': 0 },
  { '50': 1 }, { '14': 0 },
  { '39': 0 }, { '91': 0 },
  { '37': 0 }, { '34': 0 }
];

I want to sum second values to get result. like in this example result must be 2. I am using nodejs, if it helps.

Thank you.

Upvotes: 1

Views: 53

Answers (1)

Mureinik
Mureinik

Reputation: 311998

You could use Object.values to extract the value for each such object and then sum them. Using map and reduce, this can even be done in a one liner:

const total =  res.map(o => Object.values(o)[0]).reduce((a, b) => a + b, 0);

Upvotes: 1

Related Questions