Skip to content

Instantly share code, notes, and snippets.

@eugeneglova
Last active February 1, 2017 15:19
Show Gist options
  • Save eugeneglova/e3bdae2cd92a9cf208296e2807f6b94a to your computer and use it in GitHub Desktop.
Save eugeneglova/e3bdae2cd92a9cf208296e2807f6b94a to your computer and use it in GitHub Desktop.
Flatten Array ES6
/**
* Flattens deeply nested array into simple array
* @param {Array} arr - input array of numbers
* @param {Array} [acc] - accumulator to store resulting array during recursion calls
* @return {Array}
*/
const flatten = (arr, acc = []) => {
const isArray = Array.isArray(arr);
// safe check for input
if (!isArray) return arr;
// Returns accumulator when there is no input items
if (isArray && !arr.length) return acc;
// get head and tail of input array
const head = arr[0];
const tail = arr.slice(1);
// recursion call when input item is an array
if (Array.isArray(head)) {
return flatten(head.concat(tail), acc);
}
// store head into accumulator and process tail recursively
return flatten(tail, acc.concat(head));
}
console.log(flatten([[1,2,[3]],4]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment