Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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

Solution 2:

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)

Solution 3:

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( item => !likedUsers.find(item2 => item.id == item2.id));

console.log(leftusers);

Solution 4:

You can create a Set of ids that are found in likedUsers, and filter the newUsers by checking if an id is in the Set:

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

const result = newUsers.filter(function({ id }) {
  return !this.has(id) // take all users which ids is not found in the set
}, newSet(likedUsers.map(({ id }) => id))) // create a set of ids in likedUsers and assign to thisconsole.log(result)

Post a Comment for "Javascript Return Array From 2 Arrays Removing Duplicates"