Introduction
Underscore.js 101 - _.filter and _.contains

Underscore.js 101 - _.filter and _.contains

Underscore.js one of the powerful utility JS libraries out there. In this post am goin to explain some of the functions and how they can be mixed and matched to get our required functionality.

_.filter:

_.filter it looks through the list we pass and returns all the values that are truthy as per the iterator.

var odds = _.filter([1,2,3,4,5,6], function(num){ return num % 2 !== 0})<br></br>
// [1, 3, 5]

returns all the odd number on the list.

Lets take an example you have a list of strings.

var langs = ['Ruby', 'RoR', 'Python', 'Django', 'Java', 'Javascript', 'Node.js'];

You want to extract the items based on the starting letter in a word

_.filter(arr, function(i){var startLetter = i.slice(); return startLetter[0] === 'R'}) // ["Ruby", "RoR"]

for searching between more than one letter you may have to do something like this

_.filter(arr, function(i){var startLetter = i.slice(); return startLetter[0] === 'R' || startLetter[0] === 'P'}) // ["Ruby", "RoR", "Python"]

It will become more complex if we are goin to add more letters to support in this, we can minimize the complexity with one more function Underscore provides us.

_.contains:

_.contains returns true if the passed value is present in array.

_.contains([1, 2, 3], 3); // true

this can be used in our existing filter function to reduce the long list of OR conditions

_.filter(arr, function(i){var startLetter = i.slice(); return _.contains(['R', 'P'],startLetter[0])}) // ["Ruby", "RoR", "Python"]

this is easy to maintain and scalable.

Author

Vetrichelvan Jeyapalpandy

12 years of experience in web development. Javascript enthusiast. Performance is an important trait of any website, so trying to improve that wherever possible.

View Comments
Next Post

Override jQuery Mobile's default Addressbar hiding behavior

Previous Post

Image Compression and CSS Sprites - Web Developer Tools