Skip to content

Instantly share code, notes, and snippets.

@lawwantsin
Created November 26, 2017 18:17
Show Gist options
  • Save lawwantsin/ee9556d57024e2b7594148f87f7ef25b to your computer and use it in GitHub Desktop.
Save lawwantsin/ee9556d57024e2b7594148f87f7ef25b to your computer and use it in GitHub Desktop.
Recursive Array Flattener
// Recursive function that loops through each array, adding it's contents to the original until we're out of numbers.
const flatten = (integersArray, previousArray) => {
// First time it's called there is no second argument, so make that an empty array.
const newArray = previousArray || []
// integersArray needs elements or just return previous and exit recursion.
if (integersArray && integersArray.length > 0) {
integersArray.forEach(i => {
// if it's an integer, add it to the returned array.
if (typeof i === "number") {
newArray.push(i)
// If not it's an Array, so dive into it, passing our working array.
} else if (i instanceof Array) {
flatten(i, newArray)
}
})
}
return newArray
}
// Arrays need to be converted to a string to be comparable.
const prepForComparison = a => a.join(",")
// Simple DIY testing function
const testFlatten = (testArray, expectedArray) => {
const result = prepForComparison(flatten(testArray))
const expectedResult = prepForComparison(expectedArray)
if (result === expectedResult) {
console.log(`Test Passed! [${result}] does equal [${expectedArray}]`)
} else {
console.log(`Test Failed! [${result}] does NOT equal [${expectedArray}]`)
}
}
// Run the tests by passing what the array should look like as 2nd argument.
testFlatten([1, 2, [3, 4]], [1, 2, 3, 4])
testFlatten([1, 2, [3, 4], 5, [6]], [1, 2, 3, 4, 5, 6])
testFlatten([1, 2, [3, 4], 5, [6]], [1, 2, 3, 4, 5]) // Failing test, just to be complete.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment