-2

I have an array of objects that I want to reduce.

I have this array of products in my state objArr:

]
0: {item: 'Item 1', value: 1}
1: {item: 'Item 2' value: 3}
2: {item: 'Item 3', value: 5}
3: {item: 'Item 1', value: 3}
4: {item: 'Item 2', value: 5}
]

But I want it to be:

[
0: {item: 'Item 1', value: 4}
1: {item: 'Item 2' value: 8}
2: {item: 'Item 3', value: 5}
]

I only manage to delete an entire object and not just a key value pair. Can someone help me?

This is the closest I can get:

const findDuplicates = () => {

    return objArr?.reduce((arr, item) => {
        const removed = arr?.filter(i => i.item !== item.item)
        const dup = [...removed, item]
        
        return dup
    
    }, [])

}

Output:

[
0: {item: 'Item 3', value: 5}
1: {item: 'Item 1', value: 3}
2: {item: 'Item 2', value: 5}
]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Newbi
  • 1
  • 1

1 Answers1

1

As you mention, use reduce and value property to sum them up :

const groupByItem = objArr.reduce((acc, curr) => {
  if (acc[curr.item]) {
    acc[curr.item].value += curr.value;
  } else {
    acc[curr.item] = { item: curr.item, value: curr.value };
  }
  return acc;
}, {});

const groupedArray = Object.values(groupByItem);
Johan
  • 2,088
  • 2
  • 9
  • 37