按另一个数组过滤一个数组[重复]
Posted
技术标签:
【中文标题】按另一个数组过滤一个数组[重复]【英文标题】:Filter one array by another array [duplicate] 【发布时间】:2022-01-16 08:40:59 【问题描述】:const items = [[name:"p2",name:"p3", name:"p7",name:"p9",name:"p1"],[name:"p6", name:"p3",name:"p7", name:"p9",name:"p2"],[name:"p3",name:"p6", name:"p7",name:"p9",name:"p4"],[name:"p2", name:"p3",name:"p1", name:"p9",name:"p6"]]
const findObj = [name:"p1",name:"p2",name:"p6"]
从 findobj 对象中找到包含所有三个元素的集合的子数组
【问题讨论】:
或Filter array of objects based on another array in javascript 【参考方案1】:您可以使用filter
、Set
和reduce
as 轻松实现结果:
const items = [
[
name: "p2" ,
name: "p3" ,
name: "p7" ,
name: "p9" ,
name: "p1" ,
],
[
name: "p6" ,
name: "p3" ,
name: "p7" ,
name: "p9" ,
name: "p2" ,
],
[
name: "p3" ,
name: "p6" ,
name: "p7" ,
name: "p9" ,
name: "p4" ,
],
[
name: "p2" ,
name: "p3" ,
name: "p1" ,
name: "p9" ,
name: "p6" ,
],
];
const findObj = [ name: "p1" , name: "p2" , name: "p6" ];
const set = new Set(findObj.map((o) => o.name));
const result = items.filter((arr) =>
const remain = arr.reduce((acc, curr) =>
if (set.has(curr.name)) acc.add(curr.name);
return acc;
, new Set());
return remain.size === set.size;
);
console.log(result);
【讨论】:
还有一个明显的重复【参考方案2】:const items = [[name:"p2",name:"p3", name:"p7",name:"p9",name:"p1"],[name:"p6", name:"p3",name:"p7", name:"p9",name:"p2"],[name:"p3",name:"p6", name:"p7",name:"p9",name:"p4"],[name:"p2", name:"p3",name:"p1", name:"p9",name:"p6"]]
const findObj = [name:"p1",name:"p2",name:"p6"]
const result = items.filter(item=>
const childItem = item.map(childItem=>childItem.name);
let allExist=true;
findObj.forEach(obj=>
if(!childItem.includes(obj.name))
allExist=false;
)
return allExist;
)
console.log(result)
【讨论】:
【参考方案3】:使用filter
并通过使用map .map(prop=>prop.name)
或更简单的解构 .map((name)=>name)
和过滤items
从每个item
获取所有名称名称包含在findObj
const items = [[name:"p2",name:"p3", name:"p7",name:"p9",name:"p1"],[name:"p6", name:"p3",name:"p7", name:"p9",name:"p2"],[name:"p3",name:"p6", name:"p7",name:"p9",name:"p4"],[name:"p2", name:"p3",name:"p1", name:"p9",name:"p6"]]
const findObj = [name:"p1",name:"p2",name:"p6"]
const result = items.filter(item=>
const arrProp = item.map(prop=>prop.name)
const filtProp = findObj.map((name)=>name)
return filtProp.every(x=>arrProp.includes(x));
)
console.log(result)
【讨论】:
以上是关于按另一个数组过滤一个数组[重复]的主要内容,如果未能解决你的问题,请参考以下文章