10

I'm trying to sum a nested array with the reduce method. My dat array looks like this:

var data = [
    [1389740400000, 576],
    [1389741300000, 608],
    [1389742200000, 624],
    [1389743100000, 672],
    [1389744000000, 691]
];

I got this:

// es5
data.reduce(function(prev, next) { return prev + next[1]; })

// es6 syntax
data.reduce((prev, next) => prev + next[1])

However I only do need the second value from each (nested) array. Any hints or tipps for me? I'm trying to sum all values within the array.

// Edit: Thanks for the answers. The problem was, that I missed the initialValue at the end.

// es6 solution
data.reduce((prev, next) => prev + next[1], 0)
1
  • I simple way to sum all values. Commented Aug 6, 2014 at 11:08

3 Answers 3

18

Do it as following

var result = data.reduce(function (prev,next) {
    return prev + next[1];
},0);

console.log(result);//prints 3171

Here I am sending 0 as prev initially. So it will go like this

First Time  prev->0 next->[1389740400000, 576]
Second Time prev->576 next->[1389740400000, 608]

Do a console.log(prev,next) to understand much better.

If you'll see in docs you will get it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. I tried different approaches, however I missed the last element. Maybe I should read the docs more carefully. :)
3

A generic approach for all array, even if they are irregular styled.

Use: array.reduce(sum, 0)

function sum(r, a) {
    return Array.isArray(a) ? a.reduce(sum, r) : r + a;
}

console.log([
    [1389740400000, 576],
    [1389741300000, 608],
    [1389742200000, 624],
    [1389743100000, 672],
    [1389744000000, 691]
].reduce(sum, 0));

console.log([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12, [13, 14, 15, 16]]
].reduce(sum, 0));

Comments

0

What you have written would work if data is an array of integers. In your case, data is an array of arrays. Hence the return statement should operate on elements of the array:

return [previousValue[0] + currentValue[0], previousValue[1] + currentValue[1]];

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.