Skip to content

Instantly share code, notes, and snippets.

@Nosherwan
Last active September 18, 2016 09:50
Show Gist options
  • Save Nosherwan/7df35577a1c68f59898565a1995e4d38 to your computer and use it in GitHub Desktop.
Save Nosherwan/7df35577a1c68f59898565a1995e4d38 to your computer and use it in GitHub Desktop.
/**
* The following flatten method is added to the Array prototype.
* The method can directly be called on the Array object and will flatten it.
* The contents of this file can be copy pasted into a browser window console and run.
*/
Array.prototype.flatten = function () {
var array = this;
var flatArray = this.flatArray || [];
for (var i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
array[i].flatArray = flatArray;
array[i].flatten();
} else {
flatArray.push(array[i]);
}
}
return flatArray;
};
//test sample
var array = [[1, 2, [3]], 4];
var newArray = array.flatten();
console.log(newArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment