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

How to get unique combination in array of objects in javascript?

I have array of objects like this,

       let data = [
        { id: 1, name: 'a' },
        { id: 1, name: 'b'},
        { id: 1, name: 'a'},
        { id: 2, name: 'a'},
        { id: 2, name: 'b'},
        { id: 3, name: 'c'},
        { id: 3, name: 'c'}
       ]

I am trying to achieve unique combination of id and name, so expected output should be like,

output
    [   
        { id: 1, name: 'a'},
        { id: 1, name: 'b'},
        { id: 2, name: 'a'},
        { id: 2, name: 'b'},
        { id: 3, name: 'c'}
    ]

I have tried Set method but could not do it for key, value pair.
Please could someone help.
Thanks
Edit- 1
Most solutions have array of string, number or object with one key-value pair. I have two key-value pairs in object.

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

>Solution :

You can actually use Set for it, you just have to use combination of values that identifies if it is unique.

let data = [
        { id: 1, name: 'a' },
        { id: 1, name: 'b'},
        { id: 1, name: 'a'},
        { id: 2, name: 'a'},
        { id: 2, name: 'b'},
        { id: 3, name: 'c'},
        { id: 3, name: 'c'}
       ]
       
const nodup = new Set();
data.forEach(item => nodup.add(`${item.id}-${item.name}`));
console.log(Array.from(nodup))
let uniqueData = Array.from(nodup).map(item => {
    const data = item.split('-')
    return {id: data[0], name: data[1]};
});
console.log(uniqueData);

After this script, if you want to have array with objects with id and name again, you can simply create it from the result.

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