Created
April 18, 2016 15:36
-
-
Save joe-crick/43b5b30f9900af7a3679d92e2e06276e to your computer and use it in GitHub Desktop.
Flatten an Arbitrarily Nested Array
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
/** | |
* @function flattenNestedArray | |
* @description Flattens an arbitrarily nested array | |
* @param {Array} arrayToFlatten The array to flatten | |
* @return {Array} | |
*/ | |
function flattenNestedArray(arrayToFlatten){ | |
var flattenedArray = []; | |
arrayToFlatten.forEach(function(item) { | |
if(Array.isArray(item)) { | |
flattenedArray = flattenedArray.concat(flattenNestedArray(item)); | |
} else { | |
flattenedArray.push(item); | |
} | |
}); | |
return flattenedArray; | |
} | |
// TEST CODE | |
var nestedArray = [[1,2,[3,[4,5]]],6]; | |
var testArray = flattenNestedArray(nestedArray); | |
console.log(testArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment