从另一个数组中的重复项中筛选出一个数组 [英] Filter out an array from the duplicates in another array
本文介绍了从另一个数组中的重复项中筛选出一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下两个数组:
const array1 = [
{"id": 1, "color": "black"},
{"id": 2, "color": "white"},
{"id": 3, "color": "orange"}
];
const array2 = [
{"id": 2, "color": "white"},
{"id": 4, "color": "purple"}
];
如果在第二个数组中找到重复项,如何将其删除,即结果是:
How could I remove the duplicates from the first array if found in the second, i.e. the result would be:
const filtered = [
{"id": 1, "color": "black"},
{"id": 3, "color": "orange"}
];
我的代码:
const filtered = array1.map(i => array2.filter(j => i["id"] !== j["id"]))
但它似乎不起作用
推荐答案
要使代码正常工作,您可以使用filter和every
To make your code work you can use filter and every
const array1 = [ {"id": 1, "color": "black"},{"id": 2, "color": "white"},{"id": 3, "color": "orange"}];
const array2 = [{"id": 2, "color": "white"},{"id": 4, "color": "purple"}];
const filtered = array1.filter(i => array2.every(j => i["id"] !== j["id"]))
console.log(filtered)
您可以使用地图和过滤器
You can use Map and filter
const array1 = [ {"id": 1, "color": "black"},{"id": 2, "color": "white"},{"id": 3, "color": "orange"}];
const array2 = [{"id": 2, "color": "white"},{"id": 4, "color": "purple"}];
let mapper = new Map(array2.map(v=> [v.id,v]))
const final = array1.filter(({id})=> !mapper.has(id))
console.log(final)
这篇关于从另一个数组中的重复项中筛选出一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文