Skip to content

Instantly share code, notes, and snippets.

@vlazzle
Created January 27, 2012 00:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlazzle/1686086 to your computer and use it in GitHub Desktop.
Save vlazzle/1686086 to your computer and use it in GitHub Desktop.
native methods for javascript collections
var obj = {foo: 4, bar: 7};
// returns an array of keys: [ 'foo', 'bar' ]
Object.keys(obj);
var arr = [3, 6, 9];
// returns a new array: [ 4, 7 ]
arr.map(function(n) { return n + 1; });
// returns 9. AKA fold, inject, foldl. There's also reduceRight for foldr.
arr.reduce(function(memo, val) { return memo + val; });
// prints each element of n, returning nothing
arr.forEach(function(n) { console.log(n); });
// returns a subset of elements that match the predicate function
arr.filter(function(n) { return n < 8; });
// returns true iff each element passes the predicate function
arr.every(function(n) { return n % 3 == 0; });
// returns true if any element passes the predicate function
arr.some(function(n) { return n > 4; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment