Created
July 10, 2017 11:45
-
-
Save guzmonne/51bcebb7837f92fbc9a6486aa42685cf to your computer and use it in GitHub Desktop.
Arbitrary flattens a nested array.
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
| /** | |
| * Flattens an array of arbitrarily nested arrays into a flat array. | |
| * E.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
| * @param {array} array Array to be flatten. | |
| */ | |
| function flatten(array) { | |
| /** | |
| * Checks if the given array has any nested array. | |
| * @param {array} array Array to check if it is flat. | |
| */ | |
| const isFlat = (array) => array.every(x => Array.isArray(x) === false) | |
| array = array.reduce((acc, x) => acc.concat(x), []) | |
| return isFlat(array) ? array : flatten(array) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment