Last active
November 14, 2017 15:30
-
-
Save castrolem/561bca495c5261e5b7236a9d7b778976 to your computer and use it in GitHub Desktop.
Performant ES6 array of arrays flatten.
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
let arr = [[1,2,[3]], 4]; | |
const flatten = arr => { | |
let i = 0; | |
while (i < arr.length) { | |
if (Array.isArray(arr[i])) { | |
arr.splice(i, 1, ...arr[i]) | |
} else { | |
i++ | |
} | |
} | |
return arr | |
} | |
console.log(flatten(arr)); // [1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment