Javascript reduction with nested array

I am trying to summarize a nested array with a reduce method . My array of arrays is as follows:

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

I got it:

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

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

However, I need only the second value from each (nested) array. Any hints or tips for me? I am trying to sum all the values ​​in an array.

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

// es6 solution
data.reduce((prev, next) => prev + next[1], 0)
+4
source share
3 answers

Do it as follows

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

console.log(result);//prints 3171

Here I post 0as prevoriginally. So it will look like

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

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

, .

+4

, , , data - . data . , return :

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

A common approach for all arrays, even if they have the wrong style.

Using: 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));
Run code
0
source

All Articles