Maniac_1979
Maniac_1979

Reputation: 979

typescript filter array with array

Breaking my head over here.... I would like to filter an array with another array.

Use case, I have an array and that array can be filtered with dynamic checkboxes.

So far I have come up with the following code:

var filteredList = this.arrayList.filter(function(e){
           return activeCheckbuttons.filter(function(e2){
               return e2.Description != e.Description
           }).length == 0;
})

The above code works when clicking only one checkbox, however when clicking two checkboxes it doesn't.

Anybody?

Thanks,

Upvotes: 2

Views: 16932

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18292

What you need, I think, is, for each item in arrayList, to check if there is an item in activeCheckbuttons with the same description. If there is one, we add that item to the result, but, if there isn't, we ignore them:

const filteredList = this.arrayList.filter(item1 => 
     !!activeCheckbuttons.find(item2 => item1.Description === item2.Description)
);

Now, how this code works:

  • With filter we make a check for each element in the array. If the predicate for that item returns true, then the elment is returned. Is not, it is skipped.
  • Inside the predicate, we use the find method to determine whether the item we are checking exists in the activeCheckbuttons array (comparing their descriptions). find returns the first element that matches a condition, so, if it finds one, then the predicate for that item is true. If it does not find any, then returns null, which is false, and the item does not appear in the filtered array.

You'll see that I am also using the !! operator. This operator is just applying the logical not operator twice. Why? Just as way to cast an object to the value true and to cast null to false:

  • !!{} -> !(!{}) -> !(false) -> true
  • !!null -> !(!null) -> !(true) -> false

This is not really necessay, but I do like to do so to make clear in the code that I want to return true or false and not objects or null.

As stated in my comment, the problem in your code is that you are filtering the second array, removing all elements that do not have the same description as the item you are checking. Of course, if you have more than one, I suppose they're are different so the filter function returns at least one element, the main filter returns false and your result array is empty.

If this is not exactly how you need to filter, tell me and I'll modify the code accordingly

Upvotes: 8

Related Questions