Last active
September 18, 2016 09:50
-
-
Save Nosherwan/7df35577a1c68f59898565a1995e4d38 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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