Using Flat Method in javascript

ishan vimukthi
1 min readJun 17, 2021
Flat earth

If you’re into programming you must know about arrays and work with them. Have u ever came through this type of problem?

Eg :- [1,[2,[3,[4]]]]

and tried to flatten it like this

[1,2,3,4]

🤔🤔🤔🤔 ?

If the answer is yes then u know the troubles you had and u may have used recursion to resolve every nested level and flatten the array but javascript has introduced a method called flat() for arrays “Array.prototype.flat()” and it makes your life easier.

By using a flat method u can easily flatten the array up to a specified depth using flat(depthAsANumber) and you can call flat() without arguments if u want to flatten one level.

code
______
[1,[2,[3,[4]]]].flat(3)

output
_______
[1, 2, 3, 4]

but what happens if u cant count the nested levels and an array is nested deeper 😬😬😬😬?
don’t worry we can call flat() using javascript “Infinity-a numeric value representing infinity” like this flat(Infinity).
so it flattens the array for any levels.

code
______

[1,[2,[3,[4]]],1,[2,[3,[4]]],1,[2,[3,[4]]],1,[2,[3,[4,1,[2,[3,[4]]]]]],1,[2,[3,[4]]]].flat(Infinity)

output
_______
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

--

--