Javascript从2个数组中返回数组,删除重复项 [英] Javascript return array from 2 arrays removing duplicates
本文介绍了Javascript从2个数组中返回数组,删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
搜索并尝试过,到目前为止没有运气.
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} ]
我想要返回的是:
var leftUsers = [{name: 'lauren', id: 35}, {name: 'dave', id: 28} ]
基本上没有rich
对象,因为这是重复项.我只关心id
键.
basically without the rich
object as this is a duplicate. I only care about the id
key.
我尝试过:
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.
如果可能想要使用forEach/map/filter的es6解决方案
if possible would like an es6 solution using forEach/map/filter
谢谢
推荐答案
使用array.prototype.filter
过滤掉likedUsers
中存在的项目,并使用array.prototype.findIndex
检查存在性,它应该是:
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);
这篇关于Javascript从2个数组中返回数组,删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文