Last active
September 5, 2018 14:07
-
-
Save james-prado/f092e0dc0b70f9e9eaa3c594b36f094b to your computer and use it in GitHub Desktop.
Deep flatten an array
This file contains 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
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