Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

filter return combined matches

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 .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading