4Geeks logo
4Geeks logo


Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Coding Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Full-Stack Software Developer - 16w

Data Science and Machine Learning - 16 wks

Search from all Lessons

LoginGet Started

Weekly Coding Challenge

Every week, we pick a real-life project to build your portfolio and get ready for a job. All projects are built with ChatGPT as co-pilot!

Start the Challenge

Podcast: Code Sets You Free

A tech-culture podcast where you learn to fight the enemies that blocks your way to become a successful professional in tech.

Listen the podcast
← Back to How to's
Edit on Github

How to flatten an array in JavaScript?

Written by:

Flattening an array in JavaScript is the process of converting a multi-dimensional array into a single one-dimensional array which means that we move all the elements within the multi-dimensional array into a single array, this process can be done in many different ways but the easiest way to achieve this is by using the JavaScript flat() method, as shown in the following example.

1const multidimensionalArray = [ 2 1, 2, 3, 3 [ [4, 5, [6, [7]]], 8], 4 [9, [0]] 5]; 6 7const arrayFlattened = multidimensionalArray.flat(Infinity); 8console.log("Array flattened:", arrayFlattened);

code output:

1Array flattened: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

As you can see in this example, the multidimensionalArray array has many layers of array with numbers inside, to take all of those values and put them into a single array we can use the JavaScript flat() method. If you don't pass an argument to the flat() method it will only flatten the values of the first layer, to go deeper you need to specify the number of layers to flatten, for example, 5 but if you don't know how many layers you need to pass as an argument, simply pass the number Infinity, this number is the largest number JavaScript can work with and will ensure that you flatten the whole array no matter how many layers deep it is, we will explain the flat() method in more detail in just a moment.

What is flattening an array?

Flattening an array is the process of taking the nested elements within an array and putting them into a single array, in other words converting a multi-dimensional array into a single one-dimesional array, for example:

1const arrayNested = [[1, 2, 3, [4]], [5, 6, 7, [8]]];

Here we have an array that contains two other arrays inside and each of them contains another array inside, we can say that this array contains two layers deep the first layer containing two arrays [[1, 2, 3, [4]] and [5, 6, 7, [8]]. The second layer is within the inner array and contains the elements [4] and [8]. The process of flattening an array takes all the values inside the nested arrays and places them into a single one-dimensional array.

1const arrayFlattened = [1, 2, 3, 4, 5, 6, 7, 8];

Each individual element within the nested arrays is preserved when the array is completely flattened.

Ways to Flatten an Array in JavaScript

There are different ways to flatten an array in JavaScript, in the following examples we are going to see the three most popular ways to flatten an array using a recursive function, a loop, and of course the JavaScript flat() method.

Using the flat() method

Undoubtedly, the easiest and most effective way to flatten an array is by using the flat method, as its name indicates this method provides a very simple way to flatten an array no matter how many layers deep it is.

1const multidimensionalArray = [1, 2, 3, [4, 5, [6, 7, [8]], 9]]; 2 3const exampleOne = multidimensionalArray.flat(); 4const exampleTwo = multidimensionalArray.flat(2); 5const exampleThree = multidimensionalArray.flat(Infinity); 6 7console.log("flat(): ", exampleOne); 8console.log("flat(2): ", exampleTwo); 9console.log("flat(Infinity): ", exampleThree);

Code output:

1flat(): [ 1, 2, 3, 4, 5, [ 6, 7, [ 8 ] ], 9 ] 2flat(2): [ 1, 2, 3, 4, 5, 6, 7, [ 8 ], 9 ] 3flat(Infinity): [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

As shown in this example, the flat() method can be called with different arguments, if you call this method without an argument it will take the number 1 by default and will only flatten the first layer of the array. If you pass a number of layers to flatten for example 2, this method will flatten the first and the second layers of the array, in our example the first layer of numbers is [4, 5, [6, 7, [8]], 9] and the second layer is [6, 7, [8]]. Our example array has three layers deep, but in case you don't know the total amount of layers you need to pass to the flat() method you can simply use the number Infinity, this way you make sure that the method flattens the whole array no matter how many layers deep it is.

Using a JavaScript loop

Another way you can flatten an array is by using a JavaScript loop and the reduce method.

1let nestedArray = [1, 2, 3, [4, 5, [6, 7, [8]], 9]]; 2 3while (nestedArray.some((num) => Array.isArray(num))) { 4 nestedArray = nestedArray.reduce((acumulator, number) => { 5 return acumulator.concat(number); 6 }, []); 7} 8 9console.log(nestedArray); // output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

This code will flatten the array no matter how many layers deep it is, however, because we are using the some() method to ensure that the while() loop continues to execute if any of the elements within the nested array is an array, this code has a worst-case complexity of O(n^2) which makes it inefficient depending on the number of layers deep and the number of elements within the array.

Using a recursive function

Another good option for flattening an array is to use a recursive function.f

1const nestedArray = [1, 2, 3, [4, 5, [6, 7, [8]], 9]]; 2 3function flattenArray(arr) { 4 let result = []; 5 arr.forEach((item) => { 6 if (Array.isArray(item)) { 7 result = result.concat(flattenArray(item)); 8 } else { 9 result.push(item); 10 } 11 }); 12 13 return result; 14} 15 16const flattenedArray = flattenArray(nestedArray); 17console.log(flattenedArray); // output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

In this example, we're using a recursive function to put all the elements of a nested array into a single one-dimensional array. Inside the function, we are using the forEach() method to traverse the array and a conditional to ask if the current item is an array, we can do this with the syntax Array.isArray(item) this will return true if the item is an array otherwise it returns false. If the item is an array we concatenate the variable result with the result of the recursive call of the flattenArray function and if it's not an array we simply push it into the array result.


We have many options when it comes to flattening an array in JavaScript, this language provides different ways to do this process although some of them are more efficient than others, as we mentioned before, we can use loops and recursive functions to flatten an array, but is highly recommended to use the flat() method instead as it is more efficient in terms of execution and easier to use.

We trust this article has equipped you with effective strategies to flatten arrays in JavaScript. Explore more articles and resources on our blog to further refine your array manipulation skills. To delve deeper into JavaScript, don't hesitate to sign up for free at 4Geeks.com and join our FREE JavaScript course.