This page looks best with JavaScript enabled

Array.Prototype.Flat() or ES2019 Array Flat() function

 ·  ☕ 3 min read  ·  ✍️ Adesh

Flattening array in JavaScript

Flattening arrays may not be an everyday need but, it is still an important need enough to be part of most utility libraries in JavaScript. Take a look at the embedded array:-

let array = [1, 2, [3, 4, [5, 6]]];

and we want result like this:-

[1, 2, 3, 4, 5, 6];

To be honest, it becomes a nightmare to deal with such an array. Before ES2019 flat() function, there were few classical ways to deal with this monster.

The Old Classical ways

Let’s explore all the possible old classical ways of dealing with this monster array. Here you go —

— Using reduce()

1
2
3
var result = array.reduce(function(prev, curr) {
return prev.concat(curr);
});

— Using concat() and apply()

1
var result = [].concat.apply([], array);

— Using reduce()

1
2
3
var result = array.reduce(function(prev, curr) {
return prev.concat(curr);
});

— Using ES6 Spread Operator

1
var result = [].concat(...array);

The new magical way of Array.Prototype.Flat() or ES2019 Flat() function

— Array.prototype.flat()

The JavaScript array flat() function helps you to concatenate all sub-array elements of an array. In other words, it returned a flatten version of an array.

Use array.flat() to get the flattened version of the array.

1
array.flat() // [1, 2, 3, 4, [5, 6] ];

In another way, you can pass the depth level. By default, it is 1. So above can be written like below as well.

1
array.flat(1) //` `[1, 2, 3, 4, [5, 6] ] ;

But still, we did not get our result. No problem, let’s move to next depth level, say 2.

1
array.flat(2) // [1, 2, 3, 4, 5, 6 ];

Hurray! We got our result without any pain in the neck.

How to deal with complex depth level — here is the resue — Infinity

If you are not sure about array depth level or you don’t get into this crap, use Infinity as a flat parameter. Trust me, it will save your time. Wonderful!

1
2
3
const array = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12 ] ] ] ];

array.flat(Infinity);// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

Caution

Note that, if there is any empty slot in the array, the JavaScript array.flat() function will discard these empty slot while flattening them. Take a look at below example:-

1
2
3
const array = [ 'a', , , , 'b', [ 'c' , 'd' ] ];

array.flat(); // [ 'a', 'b', 'c', 'd' ];

Reference

https://v8.dev/features/array-flat-flatmap

Further Reading

Type Interference In TypeScript

Destructuring In JavaScript Can Make Your Code Short And Cleaner

This Is Why Learning New JavaScript ES6 Syntax Is So Famous!

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect