1

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...

1
  • 3
    Show the value of array. Commented Sep 1, 2016 at 10:10

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

sorry, I posted it as an answer before I saw your edit :p
0

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

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.