简体   繁体   English

Javascript 使用嵌套数组减少

[英]Javascript reduce with a nested array

I'm trying to sum a nested array with the reduce method.我正在尝试使用reduce方法对嵌套数组求和。 My dat array looks like this:我的 dat 数组如下所示:

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.问题是,我最后错过了initialValue

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

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.在这里,我最初将0作为prev发送。 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.做一个console.log(prev,next)以更好地理解。

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)使用: 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));

What you have written would work if data is an array of integers.如果data是一个整数数组,那么您所写的内容将起作用。 In your case, data is an array of arrays.在您的情况下, data是一个数组数组。 Hence the return statement should operate on elements of the array:因此 return 语句应该对数组的元素进行操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM