[英]How to sum nested array
I have an array like this我有一个这样的数组
var dataSheet = [
[{price: 200}, {price: 200}, {price: 200}],
[{price: 200}, {price: 200}],
[{price: 200}],
]
I would like to sum all the price and a result like this我想总结所有的价格和这样的结果
result = [[600], [400], [200]]
Any help would be appreciated, thanks任何帮助将不胜感激,谢谢
You could use .map()
along with .forEach()
function.您可以使用
.map()
和.forEach()
function。
var dataSheet = [ [{price: 200}, {price: 200}, {price: 200}], [{price: 200}, {price: 200}], [{price: 200}], ] const res = dataSheet.map(arr => { let sum = 0; arr.forEach(obj => sum += obj.price); return [sum]; }); console.log(res);
Principle is the same for both nested and flat arrays: just use reduce
to get sum of values in array.嵌套和平面 arrays 的原理相同:只需使用
reduce
来获取数组中值的总和。 In your case you just need to apply this mechanism to each nested array in your dataSheet
and receive new array of values.在您的情况下,您只需将此机制应用于
dataSheet
中的每个嵌套数组并接收新的值数组。 Method map
is designed exactly creating new array based on values from the source array.方法
map
旨在根据源数组中的值精确创建新数组。
So the correct answer would be to use combination of map
and reduce
.所以正确的答案是使用
map
和reduce
的组合。
var dataSheet = [ [{price: 200}, {price: 200}, {price: 200}], [{price: 200}, {price: 200}], [{price: 200}], ] var result = dataSheet.map(data => data.reduce((acc, obj) => acc += obj.price,0)); console.log(result); // [600, 400, 200]
If you really need to have result like [[600],[400],[200]]
(embedded arrays instead of just values, you just need to wrap returned values in []
, like this:如果你真的需要有类似
[[600],[400],[200]]
的结果(嵌入 arrays 而不仅仅是值,你只需要将返回值包装在[]
中,如下所示:
var dataSheet = [ [{price: 200}, {price: 200}, {price: 200}], [{price: 200}, {price: 200}], [{price: 200}], ] var result = dataSheet.map(data => [data.reduce((acc, obj) => acc += obj.price,0)]); console.log(result); // [[600], [400], [200]]
I guess map
+ reduce
is what you are looking for:)我猜
map
+ reduce
是你要找的:)
const res = dataSheet.map(el => el.reduce((acc, curr) => acc + curr.price, 0));
Or flatMap
if you need result as [600, 400, 200]:或者
flatMap
如果您需要 [600, 400, 200] 的结果:
const res = dataSheet.flatMap(el => el.reduce((acc, curr) => acc + curr.price, 0));
Use map
, reduce
and destructuring.使用
map
, reduce
和解构。
var dataSheet = [ [{ price: 200 }, { price: 200 }, { price: 200 }], [{ price: 200 }, { price: 200 }], [{ price: 200 }], ]; const result = dataSheet.map((arr) => Object.values( arr.reduce(({ price: acc }, { price }) => ({ price: acc + price })) ) ); console.log(result)
var dataSheet = [ [{price: 200}, {price: 200}, {price: 200}], [{price: 200}, {price: 200}], [{price: 200}], ]; var res = dataSheet.reduce((result, row) => result.concat([[row.reduce((sum, element) => sum + element.price, 0)]]), []); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.