Book Image

Lo-Dash Essentials

By : Adam Boduch
Book Image

Lo-Dash Essentials

By: Adam Boduch

Overview of this book

Table of Contents (15 chapters)
Lo-Dash Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Building filters


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.

Multiple filter() calls

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