JavaScript Array flat() Tutorial

In this section, we will learn what the Array flat() method is and how to use it in JavaScript.

JavaScript Arrays flat() Method: nested array and JavaScript Array flat() method

The `flat()` method is used to flatten a multidimensional array. This means if, for example, you had a two-dimensional array, after running the flat() method on it, it will become a one-dimensional array with the entire nested elements all in the same row of that result array.

Array flat() Syntax:

Array.flat(depth)

Array flat() Method Parameters:

By default `flat()` method, flattens only one level and so arrays nested beyond one level don’t get flatten. But we can provide an optional `depth` argument to tell this method to do recursive flattening up to a given depth.

For example, if we set the argument to 1 that means one level depth (This is the default value). The value 2 means two level depth. Or we can set the value to `Infinity` to completely flatten the structure regardless of how deep it is.

Array flat() Method Return Value:

The method doesn’t change the original array and instead it’ll return a single-dimensional array with the values of the target multidimensional array all as its elements.

Example: JavaScript flatten array

const arr = [
  [1,2,3,4,5],
  [6,7,8,9],
  [
    ['a','b','c'],
    ['d','e','f','g','h']
  ]
];
const flatten = arr.flat();
const flatten2 = arr.flat(2);
console.log(flatten);
console.log(flatten2);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, ["a", "b", "c"], ["d", "e", "f", "g", "h"]]

[1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h"]
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies