Skip to content

Instantly share code, notes, and snippets.

@james-prado
Last active September 5, 2018 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james-prado/f092e0dc0b70f9e9eaa3c594b36f094b to your computer and use it in GitHub Desktop.
Save james-prado/f092e0dc0b70f9e9eaa3c594b36f094b to your computer and use it in GitHub Desktop.
Deep flatten an array
const input = [[1, 2, [3]], 4];
// ––––– Option 1 –––––
function baseFlatten(array, depth, result) {
result || (result = []);
if (array == null) {
return result;
}
for (const value of array) {
if (depth > 0 && Array.isArray(value)) {
if (depth > 1) {
baseFlatten(value, depth - 1, result);
} else {
result.push(...value);
}
} else {
result[result.length] = value;
}
}
return result;
}
function deepFlatten(array) {
const INFINITY = 1 / 0;
return baseFlatten(array, INFINITY);
}
// ––––– Option 2 –––––
// function deepFlatten(arr) {
// return arr.reduce(function(prev, curr) {
// return prev.concat(Array.isArray(curr) ? flatten(curr) : curr);
// }, []);
// }
console.log(deepFlatten(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment