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
Release: 2024-12-28 10:50:15
Original
397 people have browsed it

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:

[ [ "" ], [ "" ], [ "" ], [ "" ], [ "" ], [ "" ], [ "" ] ]
Copy after login

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

[ "", "", "", ... ]
Copy after login

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: [ "", "", "", "", "", "", "" ]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template