Javascript reduce with a nested array
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.
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));