Created
September 24, 2013 19:25
-
-
Save afeld/6689958 to your computer and use it in GitHub Desktop.
understanding Underscore.js's _.map() and _.reduce()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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