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

Counting items


A variation on the previous topic—Testing truth conditions—is counting items in a collection after their values have moved through a processing chain. For example, we might need to know how many items in a collection meet the given criteria. We can get that number using a call chain.

Using length and size()

The size() function is handy because we can call it directly on a Lo-Dash wrapper. This is the preferred way to count the resulting items in our collection after our chain runs:

var object = { first: 'Charlotte', last: 'Hall' },
    array = _.range(10);

_(object)
    .omit('first')
    .size();
// → 1

_(array)
    .drop(5)
    .size();
// → 5

Here, we have array and object. The first chain uses the size() function to count the number of properties after omitting the first property. The second chain wraps the array and, after dropping 5 items, counts what's left.

Note

We can use the length property, but we have to call value() first. Using size() is just a shortcut.

Grouping...