Last active
February 7, 2019 10:46
-
-
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
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
// 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