Created
April 4, 2017 14:17
-
-
Save epicallan/f93fc1f7827144f98de961ef7842d305 to your computer and use it in GitHub Desktop.
Flatten nested array of n depth in Javascript, with tail recursion
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
// should be able to run in any ever green browser or nodejs version 5 and above | |
const flatten = (inputArray, accumulator) => { | |
inputArray.forEach((val) => { | |
if (Array.isArray(val)) { | |
flatten(val, accumulator); // tail recursion | |
} else { | |
accumulator.push(val); | |
} | |
}); | |
return accumulator; | |
}; | |
const testArray = [[1, 2, [3]], 4]; | |
const result = flatten(testArray, []); | |
console.log('flattened', result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment