Skip to content

Instantly share code, notes, and snippets.

@epicallan
Created April 4, 2017 14:17
Show Gist options
  • Save epicallan/f93fc1f7827144f98de961ef7842d305 to your computer and use it in GitHub Desktop.
Save epicallan/f93fc1f7827144f98de961ef7842d305 to your computer and use it in GitHub Desktop.
Flatten nested array of n depth in Javascript, with tail recursion
// 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