Search code examples
javascriptarraysboolean-expression

Dynamically build expression to filter Javascript array


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 ?


Solution

  • 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);