Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.