Learning Underscore JS - a quick introduction

May 7, 2014, 6:11 pm
Author: James Griffiths

If you work with JavaScript on a regular basis there’ll be times when you find yourself wondering why certain methods aren’t built into the language as default. Whether it’s certain types of data manipulation in arrays or custom objects you’ll need specialised helper functions to accomplish these ends. Writing such functionality can be tedious, prone to cross-browser issues and quite often, frustrating.

This is where Underscore JS excels as it provides a set of built-in utilities for working with JavaScript objects (whether they be Arrays, Objects [associative arrays in JavaScript], Functions, Strings or Numbers).

But do I need Underscore JS?

Good question.

As with anything JavaScript it can get a little confusing trying to navigate the sheer volume of libraries, frameworks and plug-ins that are available and then trying to figure out whether or not you need to use that particular tool.

Simply put, if you’re only looking or need to manipulate the DOM at most then stick with a library such as jQuery or Zepto. Such libraries will provide all (or most of) the functionality you need to accomplish on that front (and where they don’t there’s almost always a plug-in to fill that particular gap).

If however you need to perform specific operations on JavaScript objects (such as entity encoding strings or retrieving array keys and/or values) then definitely give Underscore JS a try. It’s built-in helpers will save you hours of research and trial and error in trying to find solutions to augment existing functionality.

What about ECMAScript 5?

As browsers prior to IE9 don’t support ECMAScript 5 (and by association won’t provide the additional methods available in this version of the language) then if you need to manipulate JavaScript objects and support older browsers then it makes sense to use a library such as Underscore JS.

The nice thing about this particular library is that if it’s used in a browser that does support ECMAScript 5 it will default to using the native functionality instead. This means you won’t lose any gains in performance (as the library doesn’t force the browser to use its own abstractions when native methods are available). Additionally the library may provide further helper methods not available in ECMAScript 5.

Installing and using Underscore

Simply download the library and include it into your web page as you would any other external library. That’s as complicated as the installation and set-up gets!

As Underscore’s methods are available in global scope access to these is through a single object - the underscore character, _ (hence the name of the library!) which makes it easy and convenient to work with (similar to jQuery’s dollar symbol $).

Let’s play!

If you’ve ever found yourself wanting to randomise or retrieve selected values from an array, simply find the size of an array or merge separate arrays without duplicating values then Underscore provides a large number of helper utilities to accomplish these.

Working with arrays

What happens when we want to find the highest and lowest values in an array? (Note: as the following operations only apply to numeric values they can’t be used on strings.)

If we want to find the minimum value in an array we can use the _.min method:

var numbers	= [1,2,3,4,5,6,7,8,9,10], min = _.min(numbers); 
console.log('Minimum value: ' + min); // Returned value is 1

And if we want to find the maximum value in an array or object? Yep, you probably guessed it - we can use the _.max method:

var numbers	= [1,2,3,4,5,6,7,8,9,10], max = _.max(numbers); 
console.log('Maximum value: ' + min); // Returned value is 10 

Filtering duplicate values

What if we want to retrieve only the unique values from an array that contains duplicate values? Underscore allows us to do just that with the _.uniq helper utility.

var repetition	    = [1,1,1,1,3,7,7,7,7,8,9,10,10,11,12,13,14,15,16,16], 
    uniqueValues	= _.uniq(repetition); 

console.log('Unique values from array: ' + uniqueValues); 
// Unique values from array: 1,3,7,8,9,10,11,12,13,14,15,16 

This helper method will also work on string values in an array:

var letters	        = [‘a’, ‘a’, ‘b’, ‘c’, ‘c’, ‘d’, ‘e’], 
    uniqueValues	= _.uniq(letters); 

console.log('Unique values from array: ' + uniqueValues); 
// Unique values from array: a,b,c,d,e 

Merging arrays

Sometimes we want to merge two separate arrays but filter out any duplicate values. Enter _.union:

var numbers 	= [1,2,3,4,5,6,7,8,9,10], 
    repetition	= [1,1,1,1,3,7,7,7,7,8,9,10,10,11,12,13,14,15,16,16], 
    union       = _.union(numbers, repetition); 

console.log('Merged array: ' + union);  // Merged array: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16  

Create a new array from a selected object value

There will be occasions when we might want to extract data from an existing Object and create an array with this.

This is relatively simple with Underscore as it allows us to use the pluck and map helper functions to accomplish this:

var catalogue = [ { name: 'Soren Kierkegaard', specialism: 'Theology' }, 
                  { name: 'Ernest Becker', specialism: 'Anthropology' }, 
                  { name: 'Eric Koston', specialism: 'Skateboarding' }, 
                  { name: 'Rodney Mullen', specialism: 'Skateboarding' }, 
                  { name: 'Purnell Whitaker', specialism: 'Boxing' }, 
                  { name: 'Sugar Ray Leonard', specialism: 'Boxing' }, 
                  { name: 'Marvin Hagler', specialism: 'Boxing' }, 
                  { name: 'Floyd Mayweather Junior', specialism: 'Boxing' } ], 
    names     = _(catalogue).pluck('name').map(function(value){ return value; }); 

console.log('Mapped values from array: ' + names); 
// Mapped values from array: Soren Kierkegaard,Ernest Becker,Eric Koston,Rodney Mullen,Purnell Whitaker,Sugar Ray Leonard,Marvin Hagler,Floyd Mayweather Junior 

Sorting an object by keys

What if we want to sort our array on a particular key? Simple, use _.sortBy:

var catalogue = [ { name: 'Soren Kierkegaard', specialism: 'Theology' }, 
                  { name: 'Ernest Becker', specialism: 'Anthropology' }, 
                  { name: 'Eric Koston', specialism: 'Skateboarding' }, 
                  { name: 'Rodney Mullen', specialism: 'Skateboarding' }, 
                  { name: 'Purnell Whitaker', specialism: 'Boxing' }, 
                  { name: 'Sugar Ray Leonard', specialism: 'Boxing' }, 
                  { name: 'Marvin Hagler', specialism: 'Boxing' }, 
                  { name: 'Floyd Mayweather Junior', specialism: 'Boxing' } ], 
    sorted    = _.sortBy(catalogue, function(item){ return item.name; }); 

console.log('Sorted values: ' + sorted); 
//Sorted Values: Eric Koston, Ernest Becker, Floyd Mayweather Junior, Marvin Hagler, Purnell Whitaker, Rodney Mullen, Soren Kierkegaard. 

In this instance we have sorted the object by the name key. Alternatively if we had sorted the object by the specialism key then the returned results would look like this:

Sorted Values: Ernest Becker, Purnell Whitaker, Sugar Ray Leonard, Marvin Hagler, Floyd Mayweather Junior, Eric Koston, Rodney Mullen, Soren Kierkegaard. 

Randomising elements in an array

This is a nice little feature made possible with the _.shuffle utility:

var numbers	= [1,2,3,4,5,6,7,8,9,10], 
    shuffle	= _.shuffle(numbers); 

console.log('Shuffled values: ' + shuffle);  // Shuffled values: 2,4,1,3,8,7,10,9,5,6. 

Re-run this script again and the returned values change. Underscore uses the Fisher-Yates shuffle algorithm to make each randomisation unique.

Does a particular value exist in an array?

Use _.contains to find out whether or not an array contains a specific value (in this example the number 1):

var numbers	 = [1,2,3,4,5,6,7,8,9,10], 
    contains = _.contains(numbers, 1); 

console.log('Contains: ' + contains); // Contains: true 

Retrieving the first value in an array

With _.first it’s child’s play:

var numbers	= [1,2,3,4,5,6,7,8,9,10], 
    first	= _.first(numbers); 

console.log('First value in array: ' + first); // First value in array: 1 

Retrieving the last value in an array

Simply use _.last:

var numbers	= [1,2,3,4,5,6,7,8,9,10], 
    last    = _.last(numbers); 

console.log('Last value in array: ' + last);  // Last value in array: 10  

The above examples are just some of the useful operations possible with Underscore JS. If you need to work with and manipulate JavaScript Objects at a low level, and ensure this works across different platforms, then give this library a shot - if you're not already doing so!

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.