简体   繁体   中英

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. If I want to add total I would do flatMap and add them togeather. 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]

You can use map and reduce.

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 (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. You can combine all these calls using map to get an array of the results.

 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:

data.map(f => f.itemDetails.reduce((acc, i) => acc + i.sizeOfBag, 0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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