A Long Time Ago in an Associative Array

Underscore has been making my life easier, and I've been explaining the Star Wars pantheon to my son so often, that it was unavoidable that the two should at some point intersect. So I thought I'd give a few simple examples of Underscore in action.

Each, wraps the native forEach Array method, if supported.

  var rebels = ['Luke', 'Leia', 'Han']; 
  _.each(rebels, function(rebel){
    console.log(rebel + ' resists the evil Empire.');
  // Luke resists the evil Empire.
  // Leia resists the evil Empire.
  // Han resists the evil Empire.

Map, returns the results of operating on the passed in Object/Array.

  var jedis = ['Luke', 'Obi Won', 'Qui Gon'];
  var result = _.map(jedis, function(jedi){
    return jedi + ' is skilled with a lightsaber.';
    [ 'Luke is skilled with a lightsaber.',
      'Obi Won is skilled with a lightsaber.',
      'Qui Gon is skilled with a lightsaber.' ]

Reduce, here we pass in an empty array as the context, to which we push our results.

  var characters = {
    Luke: 'good guy',
    Han: 'good guy',
    Darth: 'bad guy',
    Tarkin: 'bad guy'
  var goodGuys = _.reduce(characters, function(memo, val, key){
    if (val === 'good guy') {
    return memo;
  }, []);
  // [ 'Luke', 'Han' ]

Find, returns the first match in the list.

  var droids = ['R2-D2', 'C-3P0', 'R5-D4'];
  var astromech = _.find(droids, function(droid){
    return droid.match(/^R\d-D\d/);
  // R2-D2

Filter, here we return all matches within the original list.

  var droids = ['R2-D2', 'C-3P0', 'R5-D4'];
  var astromechs = _.filter(droids, function(droid){
    return droid.match(/^R\d-D\d/);
  // [ 'R2-D2', 'R5-D4' ]