Skip to content

Instantly share code, notes, and snippets.

@FredrikAugust
Created November 18, 2016 10:25
Show Gist options
  • Save FredrikAugust/57206bfab010b53f5b5acaec5bd175bc to your computer and use it in GitHub Desktop.
Save FredrikAugust/57206bfab010b53f5b5acaec5bd175bc to your computer and use it in GitHub Desktop.
Flatten an array in javascript
Array.prototype.flatten = function () {
var flat_arr = [];
var dirty = false;
for (var i = 0; i < this.length; i++) {
if (typeOf(this[i]) == "array") {
flat_arr = flat_arr.concat(this[i]);
dirty = true;
} else {
flat_arr.push(this[i]);
}
}
if (dirty) {
return flat_arr.flatten();
} else {
return flat_arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment