Flatten array

JavaScript, Array, Recursion · Oct 22, 2020

Flattens an array up to the specified depth.

  • Use recursion, decrementing depth by 1 for each level of depth.
  • Use Array.prototype.reduce() and Array.prototype.concat() to merge elements or arrays.
  • Base case, for depth equal to 1 stops recursion.
  • Omit the second argument, depth, to flatten only to a depth of 1 (single flatten).
const flatten = (arr, depth = 1) =>
  arr.reduce(
    (a, v) =>
      a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
    []
  );
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]

More like this

  • JavaScript Array Tricks

    Learn a handful of awesome tips and tricks that you can leverage in your code to make array manipulation a breeze.

    Collection · 12 snippets

  • Deep flatten array

    Deep flattens an array.

    JavaScript, Array · Oct 22, 2020

  • JSON to CSV

    Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.

    JavaScript, Array · Oct 13, 2021

  • Pull values from array based on function

    Mutates the original array to filter out the values specified, based on a given iterator function.

    JavaScript, Array · Oct 22, 2020