javascriptfilterlodashcode-readability

Lodash Filter with Multiple Functions


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!


Solution

  • 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.