Skip to content

Instantly share code, notes, and snippets.

@SourceCode
Created March 11, 2019 19:47
Show Gist options
  • Save SourceCode/a4dd1233c293961b217e6a9722e91a3c to your computer and use it in GitHub Desktop.
Save SourceCode/a4dd1233c293961b217e6a9722e91a3c to your computer and use it in GitHub Desktop.
array flatten
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