Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript return array from 2 arrays removing duplicates

Searched and tried and no luck so far.

var newUsers = [{name: 'rich', id: 25}, {name: 'lauren', id: 35}, {name: 'dave', id: 28} ]

var likedUsers = [{name: 'derek', id: 39}, {name: 'rich', id: 25}, {name: 'brian', id: 38} ]

What I want returned is:

var leftUsers = [{name: 'lauren', id: 35}, {name: 'dave', id: 28} ]

basically without the rich object as this is a duplicate. I only care about the id key.

I have tried:

newUsers.forEach((nUser) => {
    likedUsers.forEach((lUser) => {
        if (nUser.id !== lUser.id){
            leftUsers.push(nUser)
        }
    })
})

but obviously this won't work as this will just add them all as soon as they don't match.

if possible would like an es6 solution using forEach/map/filter

thanks

like image 930
The Walrus Avatar asked Jan 28 '23 18:01

The Walrus


2 Answers

With array.prototype.filter to filter out items that exists in likedUsers and array.prototype.findIndex to check the existence, it should be:

var newUsers = [{name: 'rich', id: 25}, {name: 'lauren', id: 35}, {name: 'dave', id: 28} ];
var likedUsers = [{name: 'derek', id: 39}, {name: 'rich', id: 25}, {name: 'brian', id: 38} ];

var leftUsers = newUsers.filter(u => likedUsers.findIndex(lu => lu.id === u.id) === -1);

console.log(leftUsers);
like image 158
Faly Avatar answered Jan 31 '23 08:01

Faly


You can do this with filter() and some() methods.

var newUsers = [{name: 'rich', id: 25}, {name: 'lauren', id: 35}, {name: 'dave', id: 28} ]
var likedUsers = [{name: 'derek', id: 39}, {name: 'rich', id: 25}, {name: 'brian', id: 38} ]

const result = newUsers.filter(e => !likedUsers.some(a => a.id == e.id));
console.log(result)
like image 28
Nenad Vracar Avatar answered Jan 31 '23 08:01

Nenad Vracar