Search code examples
javascriptarraysfilterinclude

Javascript - compare two arrays with filter as efficient as possible


I want to compare two arrays with filter as efficiently as possible, and also as descriptively as possible.

I am sure there must be a nice way to do this without resorting to forEach, but for the life of me I cannot find it, would anyone be kind enough to help me out of my misery?

Scenario

mainList array
id : 1, name : 'foo', categories : ["c1","c2","c3"]
id : 2, name : 'bar', categories : ["c1","c4","c5"]

userSelectListNames array "foo"

userSelectListCats array "c1","c4"

Filter on mainList categories - this is where I am stuck

return mainList.filter(item => userSelectListCats.includes(item.categories));

I want the use to see both records if he select "c1" and "c4", or "c1" And only the last one if he select "c4" and "c5" But I get hopelessly confused when trying it...

My 2 best tries..

return mainList.categories.filter(item => userSelectListCats.includes(item));

But it returns categories, and not the mainList.

return mainList.filter(item => mainList.categories.filter(item2 => userSelectListCats.includes(item2)));

I am sure there must be a nice way to do this without resorting to forEach, but for the life of me I cannot find it, would anyone be kind enough to help me out of my misery?


Solution

  • You can use Array#filter along with Array#some.

    const arr = [{id : 1, name : 'foo', categories : ["c1","c2","c3"]}, {id : 2, name : 'bar', categories : ["c1","c4","c5"]}];
    const userSelectListCats = ["c1", "c4"];
    const res = arr.filter(({categories})=>
       userSelectListCats.some(x => categories.includes(x)));
    console.log(res);