Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove only parts of duplicates in array of objects

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading