[英]Adding numbers inside array of arrays
在這里,我嘗試單獨添加數組數量,但無法達到預期的 output。 如果我想加總,我會做flatMap
並將它們加在一起。 但我想為每個數組分別添加它們。
以下是我嘗試過的片段
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);
預期 Output: [1,11]
您可以使用 map 並減少。
const res = newData.map(arr=>arr.reduce((acc,curr)=>acc+curr.sizeOfBag,0));
您對 for 循環的嘗試很接近,但是您正在循環過去最后一個索引並將索引與屬性名稱混合在一起。
for (let i = 0; i < newData.length; i++) {
newData[i] = newData[i].reduce((acc, newData) => acc + newData.sizeOfBag, 0);
}
您需要在嵌套的 arrays 上調用reduce
,而不是頂級newData
數組。 您可以使用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);
這樣做,在 map 中運行 reduce function:
data.map(f => f.itemDetails.reduce((acc, i) => acc + i.sizeOfBag, 0));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.