Last active
November 3, 2017 04:27
-
-
Save SuhairZain/2a02a56fa1f10c29ce23f829bb079aaa to your computer and use it in GitHub Desktop.
This file contains 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
// The input, an arbitrarily nested array | |
const input = [ | |
[1, 2, 3], | |
[4, 5, 6, [7, 8, [9, [10]]]] | |
]; | |
/** | |
* Recursive function to be called on arrays | |
* @param array The input array | |
*/ | |
const flatten = (array) => ( | |
// Uses JavaScript's reduce() function to combine the elements into a single value | |
array.reduce((acc, curr) => ( | |
// If the currently item (maybe the root array or a nested one) is an array itself, | |
// apply the flatten() function to it and create a new array | |
// by appending it to the elements in the accumulator using the spread operator | |
Array.isArray(curr) ? [ | |
...acc, | |
...flatten(curr), | |
] : [ // If not an array, just create a new array by appending it to the elements in the accumulator | |
...acc, | |
curr, | |
] | |
), []) | |
); | |
const result = flatten(input); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment