Here is a list that I have:
const myList = [
{ name: 'AA', quantity: 1 },
{ name: 'AA', quantity: 1 },
{ name: 'BB', quantity: 1 },
{ name: 'CC', quantity: 1 },
{ name: 'CC', quantity: 2 },
]
I want the output to be like this:
const updatedList = [
{ name: 'AA', quantity: 2 },
{ name: 'BB', quantity: 1 },
{ name: 'CC', quantity: 3 },
]
I am trying to remove duplicates and increase the quantity when a duplicate is found, but struggling with the logic.
const uniqueSet = new Set()
const finalResult = myList.reduce((acc, item) => {
if (!uniqueSet.has(item.name)) {
uniqueSet.add(item.name)
acc.push({ name: item.name, quantity: item.quantity })
}
// for (const iterator of myList) {
// if (uniqueSet.has(item.name)) {
// console.log('🚀 ~ file: Untitled-1 ~ line 15 ~ iterator', iterator)
// }
// }
console.log()
return acc
}, [])