Skip to content

Instantly share code, notes, and snippets.

@ayoola-solomon
Created November 12, 2017 22:35
Show Gist options
  • Save ayoola-solomon/613f18b1bea30a2ff590a479fbe93997 to your computer and use it in GitHub Desktop.
Save ayoola-solomon/613f18b1bea30a2ff590a479fbe93997 to your computer and use it in GitHub Desktop.
flattenArray created by Soulman - https://repl.it/@Soulman/flattenArray
const array = [[1, 2, [3]] , 4];
const flatten = (array) => {
// reduce traverses the array and we return the result
return array.reduce((acc, b) => {
// if is an array we use recursion to perform the same operations over the array we found
// else we just concat the element to the accumulator
return acc.concat(Array.isArray(b) ? flatten(b) : b);
}, []); // we initialize the accumulator on an empty array to collect all the elements
}
flatten(array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment