Skip to content

Instantly share code, notes, and snippets.

@elijahboston
Last active September 23, 2019 03:20
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 elijahboston/e565aad8693dcfb6e16c66efadca9a0a to your computer and use it in GitHub Desktop.
Save elijahboston/e565aad8693dcfb6e16c66efadca9a0a to your computer and use it in GitHub Desktop.
Flatten Multi-dimensional Arrays
// 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