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

Get unique objects if theres an array which is repeated in some other object in an array of objects

const messages = [{ id: 1, name: "Jack", users: [2,4] }, { id: 2, name: "Alex", users: [2,6] }, { id: 3, name: "John", users: [2,6] }]

Need to get unique object based on a nested array key. check if array containing same value is repeated in some other object and return only the last record which has the nested duplicate

expected answer =

[{ id: 1, name: "Jack", users: [2,4]},{id: 3, name: "John", users: [2,6] }]

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 could use a combined key of users with an object and get unique items.

const
    messages = [{ id: 1, name: "Jack", users: [2, 4] }, { id: 2, name: "Alex", users: [2, 6] }, { id: 3, name: "John", users: [2, 6] }],
    result = Object.values(messages.reduce((r, o) => {
        r[o.users.join('|')] = o;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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