Skip to content

Instantly share code, notes, and snippets.

@elijahboston

elijahboston/flatten.js

Last active Sep 23, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.