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()
|
|
— Using concat() and apply()
|
|
— Using reduce()
|
|
— Using ES6 Spread Operator
|
|
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.
|
|
In another way, you can pass the depth
level. By default, it is 1. So above can be written like below as well.
|
|
But still, we did not get our result. No problem, let’s move to next depth level, say 2.
|
|
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!
|
|
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:-
|
|
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!