Reputation: 827
I need to filter an array based an a variable number of items in another array. Say my array to be filtered looks like this :
var toBeFiltered = [
{name:"A", parentId: 0},
{name: "B", parentId: 3},
{name: "C", parentId: 0},
{name: "D", parentId: 1},
...
]
I need to filter all the elements for which parentId
is in another array (say : var filtering = [3,1,0]
, but it can have any length).
How can I build a filter expression dynamically based on the content of the filtering
array ? In this case I'd end up with this expression :
function(d){return d.parentId == 3 || d.parentId == 1 || d.parentId == 0;}
Is there any smart way to do this ? Something like concatenation of boolean expressions ?
Upvotes: 1
Views: 1565
Reputation: 48417
You can use indexOf
method which checks if an item
exists in a given array
.
indexOf
method returns first occurrence of the specified value and returns -1
if the value
is not found.
var toBeFiltered = [
{name:"A", parentId: 0},
{name: "B", parentId: 3},
{name: "C", parentId: 0},
{name: "D", parentId: 1},
{name: "E", parentId: 4}
]
var filtering = [3,1,0];
toBeFiltered=toBeFiltered.filter(a=>filtering.indexOf(a.parentId)!==-1);
console.log(toBeFiltered);
Also you can use Set
feature from ES6
.
var toBeFiltered = [
{name:"A", parentId: 0},
{name: "B", parentId: 3},
{name: "C", parentId: 0},
{name: "D", parentId: 1},
{name: "E", parentId: 4}
]
var filtering = new Set([3,1,0]);
toBeFiltered=toBeFiltered.filter(a=>filtering.has(a.parentId));
console.log(toBeFiltered);
Upvotes: 5
Reputation: 386746
You could take Array#includes
var toBeFiltered = [{ name:"A", parentId: 0 }, { name: "B", parentId: 3 }, { name: "C", parentId: 0 }, { name: "D", parentId: 1 }],
filtering = [1, 0], // to prevent to get the same array as the original
result = toBeFiltered.filter(o => filtering.includes(o.parentId));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3