Oliver Jumpertz

Infinitely Flatten Any Array

Category: JavaScript

Share this snippet to:

function flatten(...args) {
return args.flat(Infinity);
}

Usage

This is a handy helper if you sometimes deal with arrays of unknown structure. Additionally, using the spread operator on the arguments of the function, allows an arbitrary amount of parameters to be passed.

console.log(flatten([1, 2, 3], [1, [2], [1, 2]]));
// prints [1, 2, 3, 1, 2, 1, 2] to the console

Explanation

The spread operator applied to the only argument of the function basically does the following:

  1. Take the array-like arguments parameter any function explicitly has
  2. Call flat on the arguments and use the parameter Infinity

This leads to the array-like arguments object to be infinitely flattened, which lays out all arguments as a single 1-dimensional array.


Share this snippet to: