-
-
Save bananasmoothii/55e46c237dcfabdd209e162299aabd61 to your computer and use it in GitHub Desktop.
Array flatten function written in ES6 syntax
This file contains hidden or 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
function flat(array, depth = 1) { | |
let result = []; | |
if (depth !== 1) { | |
result = array; | |
for (let i = 0; i < depth; i++) { | |
result = flat(result); | |
} | |
return result; | |
} | |
for (let element of array) { | |
if (Array.isArray(element)) { | |
if (element.length > 0) { // we don't want to go in the else if the array is empty | |
for (let subElement of element) { | |
result.push(subElement); | |
} | |
} | |
} | |
else { | |
result.push(element); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment