Skip to content

Instantly share code, notes, and snippets.

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