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

JavaScript – Get the unique object from array of objects

let obj = [
    { id : 1 },
    { id : 10 },
    { brand : 12 },
    { id : 15 },
    { id : 18 },
    { image_link : 'some link' },
    { price : 10 },
    { brand : 111 },
    { image_link : 'some link 2' }
];

I have this array of object. I want filter this object so that I can get an object without duplicate keys.

I am trying this:

let uniqueIds = [];

let unique = obj.filter( (element ) => {
    
    let key = Object.keys(element)[0];                
    let isDuplicate = uniqueIds.includes(element.key);

    if (!isDuplicate) {
        uniqueIds.push(element.key);
        return true;
    }
    return false;   
});

console.log( unique )

But everytime it’s showing me :

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

[ { id: 1 } ]

My expected output:

[
    { id : 18 },
    { price : 10 },
    { brand : 111 },
    { image_link : 'some link 2' }
];

>Solution :

You can filter your array based on whether the object’s key is the last occurrence of that key (checked using lastIndexOf) in the array:

let obj = [
    { id : 1 },
    { id : 10 },
    { brand : 12 },
    { id : 15 },
    { id : 18 },
    { image_link : 'some link' },
    { price : 10 },
    { brand : 111 },
    { image_link : 'some link 2' }
];

const keys = obj.map(o => Object.keys(o)[0])

const result = obj.filter((o, i) => keys.lastIndexOf(Object.keys(o)[0]) == i)

console.log(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