Underscore.js Basics May 10th, 2013

Underscore.js is a tiny JavaScript utility library that makes working with some of the common data structures used in JavaScript much easier

Common Methods

  • _.union(myArray2, myArray3) to concatenate two arrays
  • _.uniq(myArray3) to strip duplicates from array
  • _.zip(myArray, myArray2) to return arrays where the nth value of each array is paired [0, 0], [1, 1], [2, 2], etc…
  • _.range(0,30,10) to return an array of integers (start[optional], stop, increment[optional])
  • _.size(myCollection) to return the number of items in a collection {key: value, key: value}
  • _.pluck(myCollection2, “key”) returns an array of values from a collection {key: value, key: value}
  • Filter “key: value” sets out of a collection which don’t match certain criteria
    _.filter(myCollection2, function (item) {
       return item.name.indexOf("a") !== -1;
    });
  • _.reject() is the polar opposite of filter
  • _.shuffle(myArray) to randomly shuffle an array
  • Sort “key: value” sets in a collection
    _.sortBy(myCollection3, function (item) {
       return item.name;
    });
  • _.bind(function, object, [*arguments]) to bind a function to an object, meaning that whenever the function is called, the value of this will be the object
  • _.map() to process an array into a new array
    var inputArray = ['apple', 'banana', 'pineapple'];
    var resultArray = _.map(inputArray, function(fruit){
        return fruit + 'man';
    });
    // resultArray = ['appleman','bananaman','pineappleman']
    
    // ... OR ...
    
    var createFruitMan = function(fruit){
        return fruit + 'man';
    };
    var inputArray = ['apple', 'banana', 'pineapple'];
    var resultArray = _.map(inputArray, createFruitMan);
  • _.reduce(an input array to reduce, a function to call for each array element, and a start value for the memory element) to process an array into a string (jsFiddle)

Resources