underscore – Useful JavaScript helper

The Underscore.js is a toolbox that provides over 100 functions that make you write less and do more. Most of them are for …

  • Creating and manipulating collections
  • Filter and reduce arrays
  • Reflect or replace funtions
  • Utility like UUID or Templating

Arrays

Here are some examples how to work on arrays.

// all above 50
var foo = [ 42, 1337, 13, 123, 50 ];

var fty = _( foo ).select( function ( element ) {
  return element > 50;
});

// fty = [ 1337, 123 ];

Do not allow duplicate content:

var mess = [ 1, 1, 1, 4, 1, 3, 1, 2, 3, 2 ];

var uniq = _( mess ).uniq();

// uniq = [ 1, 4, 3, 2 ];

Intersect two sets:

// [ 0, 3, 6, 9, 12 ]
var three = _.range( 0, 13, 3 );

// [ 0, 2, 4, 6, 8, 10, 12 ]
var two = _.range( 0, 13, 2 );

// intersect them
var both = _.intersection( three, two );

// both = [ 0, 6, 12 ]

Objects

Some examples how to work with JavaScript Objects.

var data = [
  { id: 1, name: "Hannah" },
  { id: 2, name: "Mike" }
];

var names = _( data ).pluck( 'name' );

// names = [ "Hannah", "Mike" ];

More: http://underscorejs.org/