Lo-Dash Essentials
上QQ阅读APP看书,第一时间看更新

Iterating over collections

Lo-Dash does a lot of iterating over collections, whether it's done explicitly by the developer, or done implicitly through a higher level Lo-Dash function. Let's take a look at the basic forEach() function:

var collection = [
    'Lois',
    'Kathryn',
    'Craig',
    'Ryan'
];

_.forEach(collection, function(name) {
    console.log(name);
});
// → 
// Lois
// Kathryn
// Craig
// Ryan

This code doesn't do much, aside from logging the value of each item in the collection. It does, however, give you a general sense of what iterative functions look like in Lo-Dash. As the name implies, for each element in the array, apply the function callback. There's more than just the current element that's passed to the callback function. We also get the current index.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Take a look at the following code:

var collection = [
    'Timothy',
    'Kelly',
    'Julia',
    'Leon'
];

_.forEach(collection, function(name, index) {
    if (name === 'Kelly') {
        console.log('Kelly Index: ' + index);
        return false;
    }
});
// → Kelly Index: 1

Returning false tells forEach() that this iteration will be the last. The index, with each iteration, is incremented and passed to the callback function as the second argument.

The forEach() function iterates over the collection in the typical left-to-right fashion. If we want the inverse behavior, we can use the cousin function, forEachRight():

var collection = [
    'Carl',
    'Lisa',
    'Raymond',
    'Rita'
];

var result = [];

_.forEachRight(collection, function(name) {
    result.push(name);
});
// →
// [
//   "Rita",
//   "Raymond",
//   "Lisa",
//   "Carl"
// ]

This type of behavior is useful when we're working with sorted collections, as is the case in the preceding code. But, let's say we wanted to render this array data in the DOM in descending order. The preceding code shows that we can render each item in a given iteration. Using the forEachRight() function for this scenario has the advantage of not having to reverse-sort the array.

However, many times this shortcut will not suffice, and you have to sort your collections. We'll take a look at the Lo-Dash functions that assist with sorting next.