Skip to content

Instantly share code, notes, and snippets.

@michaelhayman
Last active February 7, 2019 10:46
Show Gist options
  • Save michaelhayman/dad41546a3547f308fc2d93fbed42b9a to your computer and use it in GitHub Desktop.
Save michaelhayman/dad41546a3547f308fc2d93fbed42b9a to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
// flatten an array of arbitrarily nested arrays of integers
// into a flat array of integers.
// e.g. [[1,2,[3]],4] -> [1,2,3,4]
//
// could be extended to check for objects, etc. but spec says to only
// expect integers.
const flattenIntegers = (array, flattenedArray = []) => {
array.forEach(element => {
if (Array.isArray(element)) {
flattenIntegers(element, flattenedArray)
} else {
flattenedArray.push(element)
}
})
return flattenedArray
}
// Eyeball testing (would set up test suite with Mocha for this with variety of input)
const inputArray = [[1,2,[3]],4,[[[[[[[5],6]]]]]]]
const flattened = flattenIntegers(inputArray)
console.log(inputArray)
console.log(flattened)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment