Good way to chain filter functions in javascript

Store your filter functions in an array and have array.reduce() run through each filter, applying it to the data. This comes at the cost of running through all of them even when there’s no more data to filter.

const data = [...]
const filters = [f1, f2, f3, ...]
const filteredData = filters.reduce((d, f) => d.filter(f) , data)

Another way to do it is to use array.every(). This takes the inverse approach, running through the data, and checking if all filters apply. array.every() returns false as soon as one item returns false.

const data = [...]
const filters = [f1, f2, f3, ...]
const filteredData = data.filter(v => filters.every(f => f(v)))

Both are similar to your first and second samples, respectively. The only difference is it doesn’t hardcode the filters or conditions.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)