Remove duplicated objects from array but also increase quantity

Tags: , ,



I have this list:

const list = [
  { name: 'AA', quantity: 1 },
  { name: 'AA', quantity: 1 },
  { name: 'BB', quantity: 1 },
  { name: 'CC', quantity: 1 },
  { name: 'CC', quantity: 2 },
]

And the output I’m looking for should look like:

const newlist = [
  { name: 'AA', quantity: 2 },
  { name: 'BB', quantity: 1 },
  { name: 'CC', quantity: 3 },
]

This code removes duplicates, but I just can’t figure it out how to increase quantity when duplicate is present.

const setObj = new Set()
const result = list.reduce((acc, item) => {
  if (!setObj.has(item.name)) {
    setObj.add(item.name)
    acc.push({ name: item.name, quantity: item.quantity })
  }

  // for (const iterator of list) {
  //   if (setObj.has(item.name)) {
  //     console.log('🚀 ~ file: Untitled-1 ~ line 15 ~ iterator', iterator)
  //   }
  // }

  console.log()
  return acc
}, [])

Answer

Slightly different object approach that uses Object.values() to return resultant array

const list = [
  { name: 'AA', quantity: 1 },
  { name: 'AA', quantity: 1 },
  { name: 'BB', quantity: 1 },
  { name: 'CC', quantity: 1 },
  { name: 'CC', quantity: 2 },
]

const group = {};

list.forEach(e => {    
   const o =  group[e.name] = group[e.name] || {...e, quantity: 0}
   o.quantity += e.quantity
})

const res = Object.values(group)
console.log(res)


Source: stackoverflow