Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "unfiltered" array items?

Tags:

javascript

Let's say I have an array which I filter by calling myItems.filter(filterFunction1) and get some items from it.

Then I want to run another filtering function filterFunction2 against the remaining items which were not selected by filterFunction1.

Is that possible to get the remaining items that were left out after calling a filtering function?

like image 930
Sergei Basharov Avatar asked Sep 11 '25 19:09

Sergei Basharov


1 Answers

You'd have to rerun the filter with an inverted predicate, which seems wasteful. You should reduce the items instead and bin them into one of two bins:

const result = arr.reduce((res, item) => {
    res[predicate(item) ? 'a' : 'b'].push(item);
    return res;
}, { a: [], b: [] });

predicate here is the callback you'd give to filter.

like image 180
deceze Avatar answered Sep 14 '25 11:09

deceze