Search code examples
javascriptarraysecmascript-6duplicatesunique

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

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; }