Skip to content

Instantly share code, notes, and snippets.

@kirvedx
Created August 22, 2016 21:01
Show Gist options
  • Save kirvedx/2e1404a5c2c69b1e10caa1f99f09c9d6 to your computer and use it in GitHub Desktop.
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
/**
* 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