how to flatten an array in javascript

How to flatten an array in JavaScript?

Table of content

    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.


    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


    Flat array output


    Deep flatten an array

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

    JavaScript 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.

    Our Coding guides: 

    Leave a comment

    All comments are moderated before being published.

    This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.