How to flatten an array in JavaScript?

Written by Shan Shah
Updated on August 3, 2022
2 mins read
how to flatten an array in javascript

Do you know that you can flatten an array in JavaScript with one single method? This article tells you how to flatten a javascript array with the flat() array method.

Case:

I was looking for the straight solution to convert the multi-dimensional (nested) array into plan array.

So, I ended up on the solution which is flat(). Lets see how it can do wonders for you.

💥 It converts the nested array into plan array.

💪 Optionally, you can pass a depth parameter to decide your array depth. By default, it is 1.

😎 At the end, it returns the flattened new array

flatten an array in javascript

Output:

flat array output

Deep flatten an array

You can also use Infinity as parameter for unlimited number of nested array conversion.

Infinity flat array

That's it! 😀

👉 I have a simple and quick guide for you about spread operator in JavaScript. Go ahead and learn about it.

You can learn more on MDN about flat array method.

Don't forget to share with others.

How to flatten an array in JavaScript? Click To Tweet
Project Based Tutorials
Tips & Tricks
Modern Technologies
Real-World Challenges
Creative Content
Build-Apps from Scratch
Web Development Content
17+ Videos Published
Coder Champ © 2021 - 
Privacy Policy
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram