Last active
July 6, 2017 15:07
-
-
Save davisml/5e8329c13e2702cd46b837902fda29d2 to your computer and use it in GitHub Desktop.
Flattens an array of arbitrarily nested arrays
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
// Flattens an array of arbitrarily nested arrays | |
function flattenArray(inputArray) { | |
var flattenedArray = [] | |
inputArray.forEach(function(value) { | |
if (value instanceof Array) { | |
// Concat the flattened value if it is an array | |
flattenedArray = flattenedArray.concat(flatten(value)) | |
} else { | |
// Push the raw value | |
flattenedArray.push(value) | |
} | |
}) | |
return flattenedArray | |
} | |
var nestedArray = [[1,2,[3]],4] | |
// Log the result of the flattenArray function using nestedArray | |
console.log(flattenArray(nestedArray)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment