Skip to content

Instantly share code, notes, and snippets.

@bertomartin
Forked from bgreenlee/useful.js
Created February 8, 2013 20:09
Show Gist options
  • Save bertomartin/4741589 to your computer and use it in GitHub Desktop.
Save bertomartin/4741589 to your computer and use it in GitHub Desktop.
// 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