📜  array.flat - Javascript (1)

📅  最后修改于: 2023-12-03 14:59:23.200000             🧑  作者: Mango

Array.prototype.flat() in JavaScript

Introduction

The flat() method is a built-in method in JavaScript that is used to flatten nested arrays into a single dimensional array. It was introduced in ES2019 and makes it easier to work with nested arrays by simplifying them into a plain, one-dimensional array.

Syntax

The flat() method has the following syntax:

array.flat(depth)
  • array: the original array to be flattened.
  • depth: (optional) specifies the depth level of recursion to flatten. Default is 1.
Examples

Consider the following array:

const arr = [1, 2, [3, 4, [5, 6]]];

We can use the flat() method to flatten it:

const flattenedArr = arr.flat();

console.log(flattenedArr);
// Output: [1, 2, 3, 4, [5, 6]]

By default, the depth parameter is set to 1, which flattens the array to only one level. To flatten to multiple levels, we can pass a higher value for depth:

const arr = [1, 2, [3, 4, [5, 6]]];

const flattenedArr = arr.flat(2);

console.log(flattenedArr);
// Output: [1, 2, 3, 4, 5, 6]

The flat() method can also be used to remove empty spaces from an array:

const arr = [1, 2, , 4, , 6];

const flattenedArr = arr.flat();

console.log(flattenedArr);
// Output: [1, 2, 4, 6]
Conclusion

The flat() method is very useful when working with nested arrays. It allows us to easily flatten an array to a single dimensional array. It is supported in all modern browsers and can be used in both client-side and server-side applications.