Skip to content

Instantly share code, notes, and snippets.

@rebelliard
Created July 27, 2016 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebelliard/dfaeecc299b57cb886f8a2156f45c401 to your computer and use it in GitHub Desktop.
Save rebelliard/dfaeecc299b57cb886f8a2156f45c401 to your computer and use it in GitHub Desktop.
Flatten array in JavaScript
// Input:
// [[1,2,[3]],4]
// Output:
// [1,2,3,4]
Array.prototype.flatten = function() {
return this.reduce(function(previousValue, currentValue) {
let value = Array.isArray(currentValue) ? currentValue.flatten() : currentValue;
return previousValue.concat(value);
}, new Array());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment