demo
demo

Reputation: 6235

Get Sum of elements using js

I have array. Every element in this array is object, that contains also array. So I need to get sum of every items in array, that exists in array.

I have tried next :

function getSum(total, item) {
    return total + item;
}

var sum = array.reduce((total, item) => total + item.data.reduce(getSum));

But It returns not sum, but string, which starts with Object...

Upvotes: 1

Views: 3293

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

It's simply

var array = [
    {data: [1,2,3]},
    {data: [4,5,6]}
];
array.reduce((total, item) => total + item.data.reduce((a, b) => a + b), 0);
// result = 21

the second (inner) reduce doesn't have an initial value, so the

  • first call: a = data[0], b = data[1]
  • second call: a = running total, b = data[2]

see reduce documentation

the first (outer) reduce DOES need an initial value, because the items in it's callback are not numbers

Upvotes: 0

robertklep
robertklep

Reputation: 203251

You need to set an initial value for total:

var sum = array.reduce((total, item) => total + item.data.reduce(getSum, 0), 0);

If you don't, it will be initialized with the first item of the array, which in your case is an object. That's why you're getting that unexpected string.

You can even shorten your code by using total as the initial value for the second reduction:

var sum = array.reduce((total, item) => item.data.reduce(getSum, total), 0);

Upvotes: 5

Related Questions