Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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