Created
March 11, 2019 19:47
-
-
Save SourceCode/a4dd1233c293961b217e6a9722e91a3c to your computer and use it in GitHub Desktop.
array 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
const flat = (array, res) => { | |
// Short circuit the result if empty | |
if (array.length < 1 || !(array instanceof Array)) return res; | |
// Set start item | |
let s = array[0]; | |
// Set remaining items | |
let r = array.slice(1); | |
if (s instanceof Array) { | |
// This value is an array so lets merge it with the rest of items | |
s = s.concat(r); | |
return flat(s, res); | |
} | |
res.push(s); // Push our item onto the result | |
return flat(r, res); // call flat again on our remaining items and pass result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment