Skip to content

Instantly share code, notes, and snippets.

@bgreenlee
Created December 13, 2012 00:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bgreenlee/4273000 to your computer and use it in GitHub Desktop.
Save bgreenlee/4273000 to your computer and use it in GitHub Desktop.
A collection of useful Javascript functions #javascript
// sum an array, optionally providing a function to call on each element of the
// array to retrieve the value to sum
Array.prototype.sum = function(fn) {
return this.reduce(function(accum, elem) {
return accum + (fn ? fn(elem) : elem);
}, 0);
};
// flatten an array
// [1,2,[3,4]] -> [1,2,3,4]
Array.prototype.flatten = function() {
return this.reduce(function(accum, elem) { return accum.concat(elem); }, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment