Created
November 12, 2017 22:35
-
-
Save ayoola-solomon/613f18b1bea30a2ff590a479fbe93997 to your computer and use it in GitHub Desktop.
flattenArray created by Soulman - https://repl.it/@Soulman/flattenArray
This file contains hidden or 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 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