Skip to content

Instantly share code, notes, and snippets.

@joe-crick
Created April 18, 2016 15:36
Show Gist options
  • Save joe-crick/43b5b30f9900af7a3679d92e2e06276e to your computer and use it in GitHub Desktop.
Save joe-crick/43b5b30f9900af7a3679d92e2e06276e to your computer and use it in GitHub Desktop.
Flatten an Arbitrarily Nested Array
/**
* @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