JavaScript – How to Reduce Array and Add Related Integers in LWC

arrayjslightning-web-components

i have this array

const input = [
  { StockKeepingUnit: 'SKU-001', Quantity: 3 },
  { StockKeepingUnit: 'SU-002', Quantity: 5 },
  { StockKeepingUnit: 'SU-002', Quantity: 7 },
  { StockKeepingUnit: 'SKU-d7', Quantity: 2 },
  { StockKeepingUnit: 'SKU-d7', Quantity: 4 },
  { StockKeepingUnit: 'sku-899', Quantity: 1 },
  { StockKeepingUnit: 'SU-002', Quantity: 1 },
  { StockKeepingUnit: 'SU-002', Quantity: 2 },
];

but I would like for it to be like this

const input = [
  { StockKeepingUnit: 'SKU-001', Quantity: 3 },
  { StockKeepingUnit: 'SU-002', Quantity: 15 },
  { StockKeepingUnit: 'SKU-d7', Quantity: 6 },
  { StockKeepingUnit: 'sku-899', Quantity: 1 },
];

So reduce the array but add the quantities together, please, this is driving me crazy. Thank you!

Best Answer

I think that the best approach would be first doing all the sums, and the formatting as you like

Object.entries(
   input
      .reduce(
         (prev, current) => ({...prev, [current.StockKeepingUnit]: (prev[current.StockKeepingUnit] || 0) + current.Quantity}),
         {}
      )
).map(([StockKeepingUnit, Quantity]) => ({StockKeepingUnit, Quantity}))

For your second question, it would be very similar to the first answer, but instead of adding the values, you should add them to lists, and then reduce the items again in order to calculate the average

Object.entries(
   input
      .reduce(
         (prev, current) => ({...prev, [current.StockKeepingUnit]: [...(prev[current.StockKeepingUnit] || []), current.Quantity]}),
         {}
      )
)
    .map(([StockKeepingUnit, Quantity]) => ({StockKeepingUnit, Average: Quantity.reduce((a, b) => a + b, 0) / Quantity.length}))
Related Topic