Skip to content

Instantly share code, notes, and snippets.

@davisml
Last active July 6, 2017 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davisml/5e8329c13e2702cd46b837902fda29d2 to your computer and use it in GitHub Desktop.
Save davisml/5e8329c13e2702cd46b837902fda29d2 to your computer and use it in GitHub Desktop.
Flattens an array of arbitrarily nested arrays
// 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