简体   繁体   English

JS如何减少归纳数组的索引?

[英]JS How to make a reduce to sum a index of a array?

I need help to learn how to make a reduce to a array like this: 我需要帮助来学习如何使约简成这样的数组:

a=[ ["ww","fsf",40],["ww","fsf",30],["ww","fsf",10]]

I want to learn how to sum the 40+30+10 using the method reduce. 我想学习如何使用reduce方法将40 + 30 + 10求和。 I know how to do it if the array was [40,30,10]. 我知道如果数组为[40,30,10]怎么办。 Can anyone help me? 谁能帮我? Thank you. 谢谢。

.reduce applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value: .reduce对一个累加器和数组的每个值(从左到右)应用一个函数,以将其减小为单个值:

a.reduce(callback[, initialValue])

Your values will be arrays: 您的值将是数组:

["ww","fsf",40]
["ww","fsf",30]
["ww","fsf",10]

So you can use: 因此,您可以使用:

a.reduce(function(sum, value) {
  return sum + value[2];
}, 0);

Or using ES6 new arrow functions : 或使用ES6新箭头功能

 a.reduce((sum, value) => sum + value[2], 0);
a.reduce((sum, row) => sum + row[row.length - 1], 0)

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

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