Guide to Flatten array in JavaScript

JavaScript , 0 Comments

In this article, I’ll show you the how-to flatten array in JavaScript in detail by examples and will give every possible example of flat() function of JavaScript. flat function introduced in ECMAScript 2019

Flattering an array in JavaScript made easy using flat() array function. The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Before flat method introduced we use concat and many other methods to flatten the array.

var animals = [
  ["Lion"],
  ["Bear"],
  ["Deer"]
];
var merged = [].concat.apply([], animals);

console.log(merged); //  ["Lion", "Bear", "Deer"]

But now we can use flat() method to flatten an array. like below:

var animals = [
  ["Lion"],
  ["Bear"],
  ["Deer"]
];
var merged = animals.flat();

console.log(merged); //  ["Lion", "Bear", "Deer"]

Parameter

flat() method receives only one parameter is depth it specifies how deep a nested array structure should be flattened. By default, its value is 1. The return value is the new flattened array. I’ll show you some examples of flattening nested arrays.

Examples of Flattening nested arrays

var arr = [1, 2, [3, 4]];
arr.flat(); 
// [1, 2, 3, 4]

In the above example, the nesting level of the array is 1 so, you don’t even have to specify the depth in flat() method because it takes 1 by default and the output is [1, 2, 3, 4].

What if you did not pass any parameter to flat() method with multidimensional array?

var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
// [1, 2, 3, 4, [5, 6]]

In the example above, we did not pass any parameter to flat() function when flattering 2 levels of an array so it will flatten till level 1 and leave rest as it is, the output of the above example is [1, 2, 3, 4, [5, 6]]. If you want to fix this completely you have to pass depth level 2 in the flat() method, see the below example.

var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat(2);
// [1, 2, 3, 4, 5, 6]

Infinite depth level

What if the depth of an array is infinite or dynamic that you don’t know? In that case, you just need to pass Infinity to flat() method and it will flatten the array to any level of depth. See the example below:

var arr = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Flattening and array holes

The flat method also removes the empty slots in arrays. Example below:

var arr = [1, 2, , 4, 5];
arr.flat();
// [1, 2, 4, 5]

Browser Support

Method
flat()69No621256

Thank you for reading and support. Please share it with love.

Spread the love
  • 1
    Share

Leave a Reply

avatar
  Subscribe  
Notify of