Teja
Teja

Reputation: 171

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]

Upvotes: 0

Views: 102

Answers (3)

Unmitigated
Unmitigated

Reputation: 89224

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);
}

Upvotes: 1

Ray Caballero
Ray Caballero

Reputation: 443

Do it like this, run the reduce function inside your map:

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

Upvotes: 1

Barmar
Barmar

Reputation: 780871

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);

Upvotes: 1

Related Questions