给出以下两个数组:
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 = [
{"id": 1, "color": "black"},
{"id": 3, "color": "orange"}
];
我的代码:
const filtered = array1.map(i => array2.filter(j => i["id"] !== j["id"]))
但它似乎不起作用
答案 0 :(得分:1)
要使代码正常工作,您可以使用过滤器和每个
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)
您可以使用地图和过滤器
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)
答案 1 :(得分:0)
我们可以使用Array.prototype.filter
来过滤第一个数组。可以通过具有不同时间复杂度的各种方式来构造过滤条件:
Array.prototype.findIndex
的线性时间,该时间将检查当前对象是否包含在第二个数组中:
const array1 = [{"id": 1, "color": "black"}, {"id": 2, "color": "white"}, {"id": 3, "color": "orange"}];
const array2 = [{"id": 2, "color": "white"}, {"id": 4, "color": "purple"}];
function filterArray(array1, array2,){
return array1.filter( ({id}) => array2.findIndex((o) => id === o.id ) < 0);
}
console.log(filterArray(array1, array2));
Set
来高效地完成此操作:
const array1 = [{"id": 1, "color": "black"}, {"id": 2, "color": "white"}, {"id": 3, "color": "orange"}];
const array2 = [{"id": 2, "color": "white"}, {"id": 4, "color": "purple"}];
function filterArrayUsingSet(array1, array2){
const lookup = new Set(array2.map(({id}) => id));
return array1.filter( ({id}) => !lookup.has(id) );
}
console.log(filterArrayUsingSet(array1, array2));
id
的{{1}},这也将是恒定时间查找:
array2
答案 2 :(得分:0)
如果您希望仅基于“ id”删除重复项,则可以使用Array.filter()
和Array.find()
或Array.some()
-
const filtered = array1.filter(x => !array2.find( y => y.id===x.id));
OR
const filtered = array1.filter(x => !array2.some( y => y.id===x.id));
选中this JS Bin进行游戏。
答案 3 :(得分:0)
如果要基于第二个数组中找到的任何键值匹配来过滤数组,则使用forEach和every的解决方案:
\ScraperProject
|-\ScrEnv
|-\Include
|-\Lib
|-\site-packages
|-\bs4
|-\requests
|-\Scripts
|-scraper.py
|-pyvenv.cfg
答案 4 :(得分:-1)
你很近。但是您必须切换map
和filter
。
const filtered = array1.filter( color => array2.map(item => item.id).includes(color.id));