Javascript从2个数组中返回数组,删除重复项

时间:2018-01-31 10:31:57

标签: javascript arrays ecmascript-6 duplicates javascript-objects

搜索并尝试过,到目前为止没有运气。

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密钥。

我试过了:

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

但显然这不起作用,因为只要它们不匹配就会将它们全部添加。

如果可能,请使用forEach / map / filter

的es6解决方案

感谢

4 个答案:

答案 0 :(得分:3)

使用array.prototype.filter过滤掉likedUsersarray.prototype.findIndex中存在的项目来检查是否存在,它应该是:



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




答案 1 :(得分:2)

您可以使用filter()some()方法执行此操作。



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)




答案 2 :(得分:0)

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

答案 3 :(得分:0)

您可以通过检查ID是否在集合中来创建likedUsersSet newUsers中的filter个ID:

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
}, new Set(likedUsers.map(({ id }) => id))) // create a set of ids in likedUsers and assign to this

console.log(result)