Reputation:
Trying to figure out the cleanest way to do the following:
I'm filtering some results twice, and I'm using Lodash filter to do so. Currently, my code looks like:
resultsOne = _.filter(results, functionOne);
resultsTwo = _.filter(resultsOne, functionTwo);
I realize I could combine functionOne and functionTwo, but I like them broken apart for readability. Is there a best practice for filtering with two functions, either using Lodash or plain ol' Javascript?
Thanks!
Upvotes: 5
Views: 5725
Reputation: 136
something like this perhaps?
results.filter(functionOne).filter(functionTwo);|
Upvotes: 1
Reputation: 57964
You could use Lodash to chain these two filters together, with the _(…)
constructor, or more correctly, wrapper:
let filtered = _(results).filter(functionOne).filter(functionTwo).value()
The _(…)
wrapper wraps a value, the array in this case, and allows it to be chained with other functions such as _.filter
. The array would be passed as the array to be filtered, and the function as the predicate. The value()
call at the end unwraps the value.
Of course, with ES5, this operation becomes extremely trivial, and Lodash can create unnecessary clutter:
let filtered = results.filter(functionOne).filter(functionTwo);
This reduces library dependence with builtin methods and is easily chainable without wrappers.
And you could even use vanilla JavaScript to combine them:
let filtered = results.filter(result => functionOne(result) && functionTwo(result))
This checks against both functions. This is similar to _.overEvery
suggested by Ori Diori which composes an arbitrary number of predicates into a single filter predicate.
Upvotes: 0
Reputation: 192287
Using lodash
You can create a filtering function using _.overEvery()
, and use it in the filter:
var ff = _.overEvery([functionOne, functionTwo]);
var filteredResults = results.filter(ff)
Vanilla JS
Create an array of filter functions, and apply them to a value using Array#every:
var filters = [functionOne, functionTwo];
filterdResults = results.filter(function(item) {
return filters.every(function(ff) {
return ff(item);
});
});
Upvotes: 9