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 the second occurrence of array object with same name

I have this array (java script array of objects)

users=[{name:'arrow',age:50,id:444}
       {name:'bow',age:66,id:884}
       {name:'arrow',age:30,id:99},
       {name:'apple',age:50,id:999}
       {name:'bow',age:50,id:9669}]

I want to remove second occurrence of same name , in this case , I want to remove {name:'arrow',age:30,id:99} and {name:'bow',age:50,id:9669} and retain first occurrences{name:'arrow',age:50,id:444} and {name:'bow',age:66,id:884}

Resulting array should 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

users=     [{name:'arrow',age:50,id:444}
           {name:'bow',age:66,id:884},
           {name:'apple',age:50,id:999}]
       

>Solution :

const users = [
    { name: 'arrow', age: 50, id: 444 },
    { name: 'bow', age: 66, id: 884 },
    { name: 'arrow', age: 30, id: 99 },
    { name: 'apple', age: 50, id: 999 },
    { name: 'bow', age: 50, id: 9669 }
]

const uniqueUsers = users.reduce((acc, user) => {
    if (!acc.find(u => u.name === user.name)) {
        acc.push(user)
    }
    return acc
}, [])
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