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}
]