A powerful use of chained function calls is building filters that successively filter out unwanted items from a larger collection. Let's say that you already have a piece of code that's using the filter()
function on a collection. But now you need to alter that filtering operation, perhaps by adding additional constraints. Rather than messing around with the existing filter()
code that you know works, you can build a filter chain.
The simplest approach to assembling filter chains is to join together multiple calls to the filter()
function. Here's an example of what that might look like:
var collection = [ { name: 'Ellen', age: 20, enabled: true }, { name: 'Heidi', age: 24, enabled: false }, { name: 'Roy', age: 21, enabled: true }, { name: 'Garry', age: 23, enabled: false } ]; _(collection) .filter('enabled') .filter(function(item) { return item.age >= 21; }) .value(); // → [ { name: "Roy", age: 21, enabled:...