Skip to content

Instantly share code, notes, and snippets.

@afeld
Created September 24, 2013 19:25
Show Gist options
  • Save afeld/6689958 to your computer and use it in GitHub Desktop.
Save afeld/6689958 to your computer and use it in GitHub Desktop.
understanding Underscore.js's _.map() and _.reduce()
// this...
var doubles = [];
_.each([1,2,3], function(val){
doubles.push(val * 2);
});
// ...and this...
var doubles = _.map([1,2,3], function(val){
return val * 2;
});
// ...are equivalent
// so is this...
var numMales = 0;
_.each(people, function(person){
if (person.gender === 'M') {
numMales++;
}
});
// ...and this
var numMales = _.reduce(people, function(sum, person){
if (person.gender === 'M') {
return sum + 1;
} else {
return sum;
}
}, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment