Flattening an array means making it one-dimensional. The easiest way to flatten an array is via Array.prototype.flat
.
// multi-dimensional array
const multiDimensional = [1, 2, [3, 4]];
// flat, one-dimensional array
const oneDimensional = [1, 2, 3, 4];
For many years, doing this in javascript required the use of concat, spread, or reduce. Not anymore.
Flatten with Array.prototype.flat
This method does exactly what you’d expect:
const multiDimensional = [1, 2, [3, 4]];
const oneDimensional = multiDimensional.flat();
// [1, 2, 3, 4]
By default, flat
only flattens one level deep:
const multiDimensional = [1, [2, [3, 4]]];
// [3, 4] is nested two levels deep
multiDimensional.flat();
// [1, 2, [3, 4]]
But flat
accepts an argument specifying depth:
const multiDimensional = [1, [2, [3, 4]]];
multiDimensional.flat(2);
// [1, 2, 3, 4]
That’s it!
Helpful Links
- Other ways to flatten an array – flexiple