arr = [{name: "tom", tools:["spanner", "hammer", "screwdriver"]},
{name: "john", tools:["Mallet", "hammer", "screwdriver"]},
{name: "phil", tools:["Mallet", "Drill", "screwdriver"]}]
private filterObjectArray(arr: any, filterArr: any): any {
return arr.filter((el: any) =>
filterArr.some(
(f: any) =>
el.tools.toString()?.toLowerCase().indexOf(f.name?.toLowerCase()) >= 0
)
);
}
My filter is similar to the above, at the moment if my filter returned filterArr = [{name: "screwdriver"}, {name: "hammer"}]
then all objects would be returned as they all have at least one match in screwdriver
.
However, how do I make it that only objects that has both filter properties display e.g. in the above I expect only the two objects tom
and john
return as they both have a screwdriver
and hammer
, whereas phil
only has a screwdriver
.
CodePudding user response:
Here is a solution in JS. You can use every
here to check if that every filter is included in the tools array
let arr = [{name: "tom", tools:["spanner", "hammer", "screwdriver"]},
{name: "john", tools:["Mallet", "hammer", "screwdriver"]},
{name: "phil", tools:["Mallet", "Drill", "screwdriver"]}]
let filterArr = [{name: "screwdriver"}, {name: "hammer"}]
let res = arr.filter(({tools}) => filterArr.every(({name}) => tools.includes(name)))
console.log(res)
CodePudding user response:
You can use every instead of the includes(index >= 0)
It means
everything match then true otherwise false
private filterObjectArray(arr: any, filterArr: any): any {
return arr.filter((el: any) => filterArr.every((f: any) => el.tools.includes(f.name)))
}