January 2020
Intermediate to advanced
470 pages
11h 13m
English
As we did before with map(), we can also create our own version of filter() by using reduce(). The idea is similar: loop through all the elements of the input array, apply the predicate to it, and if the result is true, add the original element to the output array. When the loop is done, the output array will only have those elements for which the predicate was true:
const myFilter = (arr, fn) => arr.reduce((x, y) => (fn(y) ? x.concat(y) : x), []);
We can quickly see that our function works as expected:
console.log(myFilter(serviceResult.accountsData, v => v.balance < 0));// two objects, with id's J140793A and M120396V
The output is the same pair of accounts that we saw earlier in this section.
Read now
Unlock full access