Home >Web Front-end >JS Tutorial >How Can I Flatten a Nested Array in JavaScript?

How Can I Flatten a Nested Array in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 10:50:15402browse

How Can I Flatten a Nested Array in JavaScript?

Merging/Flattening an Array of Arrays

Problem:

You have a JavaScript array containing an array of inner arrays, such as:

[ [ "" ], [ "" ], [ "" ], [ "" ], [ "" ], [ "" ], [ "" ] ]

and you want to merge them into a single, flattened array:

[ "", "", "", ... ]

Solution:

ES2019 Array.prototype.flat() Method:

ES2019 introduced the Array.prototype.flat() method, which provides a simple and concise way to flatten an array of arrays. It is compatible with most modern environments, including Node.js version 11 and above, but it is not supported in Internet Explorer.

const arrays = [
      [""],
      [""],
      [""],
      [""],
      [""],
      [""],
      [""]
    ];
const mergedArray = arrays.flat();

console.log(mergedArray); // Logs: [ "", "", "", "", "", "", "" ]

The flat() method can also take a depth parameter, which specifies how deep the nested array structure should be flattened. By default, it is set to 1, meaning it will flatten one level of nested arrays. To flatten all levels, you can pass Infinity as the depth parameter.

The above is the detailed content of How Can I Flatten a Nested Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn