Skip to content

Instantly share code, notes, and snippets.

@sa-adebayo
Created December 14, 2017 16:15
Show Gist options
  • Save sa-adebayo/e1afaa6bfb36bbad269d43b48f582876 to your computer and use it in GitHub Desktop.
Save sa-adebayo/e1afaa6bfb36bbad269d43b48f582876 to your computer and use it in GitHub Desktop.
A JS function to recursively flatten an array
/**
* deeply flattens the content of an array recursively
* @param {Array} arr - the array to flatten
* @param {Array} acc - the accumulator array object
*/
function DeepFlatten(arr, acc) {
if (!(arr instanceof Array)) return acc.push(arr);
arr.forEach((value) => DeepFlatten(value, acc));
return acc;
}
/**
* flattens the content of an array
* @param {Array} arr - the array to flatten
*/
function flatten(arr) {
return DeepFlatten(arr, []);
}
var a = [
1,
2,
[3, 4, 5],
6,
7,
[8, 9, 10],
[11],
12,
13,
14,
[15, 16, 17, [18, 19, [20, 21, [22, 23, 24], 25, [26, [27, 28]], 29, 30]]],
];
console.log(flatten(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment