Last active
September 23, 2019 03:20
-
-
Save elijahboston/e565aad8693dcfb6e16c66efadca9a0a to your computer and use it in GitHub Desktop.
Flatten Multi-dimensional Arrays
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
// Full source and tests available from https://github.com/elijahboston/flatten | |
// Flatten a multi-dimensional array | |
// by recursively concatenating non-Array | |
// elements | |
// Ex: flatten([0, [1, 2], [3, 4]]) -> [0, 1, 2, 3, 4,] | |
const flatten = arr => | |
// Use a reducer since its behavior is well | |
// suited to recursion | |
arr.reduce( | |
(acc, curr) => | |
// Determine whether this is an array | |
Array.isArray(curr) | |
? // If it is we append the recursion result | |
// to the accumulated value -- which will eventually | |
// return a non-Array value | |
acc.concat(flatten(curr)) | |
: // Otherwise, append the non-Array result | |
// to the accumulated value | |
acc.concat(curr), | |
// Initialize accumulator to an empty array | |
[] | |
); | |
module.exports = flatten; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment