Created
August 22, 2016 21:01
-
-
Save kirvedx/2e1404a5c2c69b1e10caa1f99f09c9d6 to your computer and use it in GitHub Desktop.
denest.js - a method to flatten an array which possibly contains more arrays
This file contains 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
/** | |
* denest | |
* | |
* This function will take an array with possible nested arrays | |
* and flatten it | |
* | |
* provided: Array of values, possibly containing more arrays | |
* result: Array of values, as taken from provided in order to 'flatten' its values. This | |
* argument is available when this method calls itself. | |
* | |
* Returns result (Array) - The provided array as it would be if it were 'flattened'. | |
*/ | |
function denest( provided, result ) | |
{ | |
if( !result ) | |
{ | |
result = []; | |
} | |
for( var i=0; i < provided.length; i++ ) | |
{ | |
if( provided[i].constructor == Array ) | |
{ | |
denest( provided[i], result ); | |
} | |
else | |
{ | |
result.push( provided[i] ); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment