Array.prototye.flat() or ES2019 array
flat() function. How array.prototype.flat() or flat() function can make programmer’s life easier.
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()[crayon-5f5743218a3ab101040761/]
— Using concat() and apply()[crayon-5f5743218a3b5645751919/]
— Using reduce()[crayon-5f5743218a3b8941086535/]
— Using ES6 Spread Operator[crayon-5f5743218a3ba384179940/]
The new magical way of Array.Prototype.Flat() or ES2019 Flat() function
flat() function helps you to concatenate all sub-array elements of an array. In other words, it returned a flatten version of an array.
array.flat() to get the flattened version of the array.
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, 2, 3, 4, [5, 6] ] ;
But still, we did not get our result. No problem, let’s move to next depth level, say 2.
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!
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];
const array = [ 'a', , , , 'b', [ 'c' , 'd' ] ];
array.flat(); // [ 'a', 'b', 'c', 'd' ];