1

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 ?

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Simple and elegant. I hadn't thought about this. Thanks.
3

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; }

1 Comment

Thank you. I accepted the other answer because includes is less supported than indexOf.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.