Skip to content

Instantly share code, notes, and snippets.

@SuhairZain
Last active November 3, 2017 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SuhairZain/2a02a56fa1f10c29ce23f829bb079aaa to your computer and use it in GitHub Desktop.
Save SuhairZain/2a02a56fa1f10c29ce23f829bb079aaa to your computer and use it in GitHub Desktop.
// 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