[英]Adding numbers inside array of arrays
Here I'm trying to add number of array separately, but I'm not able to achieve the expected output.在这里,我尝试单独添加数组数量,但无法达到预期的 output。 If I want to add total I would do flatMap
and add them togeather.如果我想加总,我会做flatMap
并将它们加在一起。 But I want add them separately for each array.但我想为每个数组分别添加它们。
Below is the snippet for what I have tried以下是我尝试过的片段
const data = [{ "itemDetails": [{ "sizeOfBag": 1, "numberOfBags": 1, "quantityInBag": 1.0 }] }, { "itemDetails": [{ "sizeOfBag": 1, "numberOfBags": 1, "quantityInBag": 1.0 }, { "sizeOfBag": 10, "numberOfBags": 1, "quantityInBag": 1.0 } ], } ] const newData = data.map(f => f.itemDetails); console.log(newData); for (let i = 0; i <= newData.length; i++) { const addData = newData.reduce((acc, newData) => acc + newData[i].sizeOfBag, 0); } console.log(addData);
Expected Output: [1,11]
预期 Output: [1,11]
You can use map and reduce.您可以使用 map 并减少。
const res = newData.map(arr=>arr.reduce((acc,curr)=>acc+curr.sizeOfBag,0));
Your attempt with the for loop is close, but you are looping past the last index and mixing up your index with property names.您对 for 循环的尝试很接近,但是您正在循环过去最后一个索引并将索引与属性名称混合在一起。
for (let i = 0; i < newData.length; i++) {
newData[i] = newData[i].reduce((acc, newData) => acc + newData.sizeOfBag, 0);
}
You need to call reduce
on the nested arrays, not the top-level newData
array.您需要在嵌套的 arrays 上调用reduce
,而不是顶级newData
数组。 You can combine all these calls using map
to get an array of the results.您可以使用map
组合所有这些调用以获得结果数组。
const data = [{ "itemDetails": [{ "sizeOfBag": 1, "numberOfBags": 1, "quantityInBag": 1.0 }] }, { "itemDetails": [{ "sizeOfBag": 1, "numberOfBags": 1, "quantityInBag": 1.0 }, { "sizeOfBag": 10, "numberOfBags": 1, "quantityInBag": 1.0 } ], } ] const newData = data.map(f => f.itemDetails); console.log(newData); const addData = newData.map(d => d.reduce((acc, x) => acc + x.sizeOfBag, 0)); console.log(addData);
Do it like this, run the reduce function inside your map:这样做,在 map 中运行 reduce function:
data.map(f => f.itemDetails.reduce((acc, i) => acc + i.sizeOfBag, 0));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.