Skip to content

Flattening Nested Arrays In Javascript With flat() Method

Flattening Nested Arrays In Javascript With flat() Method

Learn how to flatten nested arrays with all the elements concatenated using the flat() method.

Have you ever looked at some arrays and wondering why is this item nested 6 levels deep, where a multidimensional array is not even needed?

I have an array of animals in the example below where it has array holes and some nested arrays too.

const animals = ["馃惗 dog", "馃惐 cat", , [[[["馃惛 frog", "馃 scorpion"]]]]];

For some reason, I have a "馃惛 frog" and a "馃 scorpion" in a nested array. There is also an empty element at the index[2].
My desired array should look like this:

const animals = ["馃惗 dog", "馃惐 cat", "馃惛 frog", "馃 scorpion"];

How To Flatten Arrays With The flat() Method

In Javascript, we can flatten an array using the flat() method. It takes an optional depth parameter to specify how deep a nested array should be flattened. the default value is 1.

const animals = ["馃惗 dog", "馃惐 cat", , [[[["馃惛 frog", "馃 scorpion"]]]]];

const flattenedArray = animals.flat(Infinity);

console.log(flattenedArray);
// ["馃惗 dog", "馃惐 cat", "馃惛 frog", "馃 scorpion"];

Since I wanted to flatten the whole array and have no nesting, I passed Infinity as the argument.

If you want to learn more about the flat() method, follow the rest of the article.

More Examples of Flattening Arrays Using The flat() Method

Let’s create define some multidimensional arrays and flatten them by specifying the depth level.

const arr1 = ["馃惗 dog", "馃惐 cat", , [[[["馃惛 frog", "馃 scorpion"]]]]];

console.log(arr1.flat(3));
// [ "馃惗 dog", "馃惐 cat", [ "馃惛 frog", "馃 scorpion" ] ]

// Adding some animals to the array
const arr2 = [
  "馃惗 dog",
  "馃惐 cat",
  ,
  [["馃 fox", "馃惣 panda", [["馃惛 frog", "馃 scorpion"]]]],
];

console.log(arr2.flat(1));
// [ "馃惗 dog", "馃惐 cat", [ "馃 fox", "馃惣 panda", [ ["馃惛 frog", "馃 scorpion"] ] ] ]

console.log(arr2.flat(2));
// [ "馃惗 dog", "馃惐 cat", "馃 fox", "馃惣 panda", [ ["馃惛 frog", "馃 scorpion"] ] ]

console.log(arr2.flat(4));
// [ "馃惗 dog", "馃惐 cat", "馃 fox", "馃惣 panda", "馃惛 frog", "馃 scorpion" ]