each
Iterates over a list of elements, yielding each in turn to an iteratee function. Each invocation of iteratee is called with three arguments: (element, index, list).
In JavaScript
for(var i = 0; i < someArray.length; i++) { var someThing = someArray[i]; doSomething(someArray[i]); }
In undescore
_.each(someArray, function(someThing) { doSomething(someThing); })
That’s underscorejs in action. Clean, easy to read, short, no variables, stacks of semi-colons… just plain nice.
map
Produces a new array of values by mapping each value in list through a transformation function.
In undescore
var result = _.map(someArray, function(someThing) { return doSomething(someThing); })
filter
Looks through each value in the list, returning an array of all the values that pass a truth test (predicate).
In JavaScript
var i, result = []; for(i = 0; i < someArray.length; i++) { var someThing = someArray[i]; if(someThing.isVisible === true) { result.push(someArray[i]); } }
In undescore
var result = _.filter(someArray, function(someThing) { return someThing.isVisible === true; })
reduce
Reduce boils down a list of values into a single value.
In JavaScript
var total = 0, coefficient = 0.24, items = [5, 4, 3, 7], i; for(i = 0; i < items.length; i++) { var item = items[i]; total += item * coefficient; }
In undescore
var total = 0, coefficient = 0.24, items = [5, 4, 3, 7], i; total = _.reduce(items, function(prevTotal, item) { return prevTotal + (item * coefficient); }, 0)