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

How Can I Flatten a JavaScript Array of Arrays?

Barbara Streisand
Release: 2024-12-31 06:23:13
Original
290 people have browsed it

How Can I Flatten a JavaScript Array of Arrays?

Merge/Flatten an Array of Arrays

Problem Statement:

You have a JavaScript array that contains subarrays of strings, such as:

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

Your goal is to combine these subarrays into a single, flattened array, resulting in:

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

Solution using Array.prototype.flat():

ES2019 introduced the Array.prototype.flat() method, which offers a straightforward way to flatten arrays. It takes an optional parameter that specifies the level of flattening. By default, it flattens one level, which is sufficient for this use case.

const arrays = [
  [""],
  [""],
  [""],
  [""],
  [""],
  [""],
  [""]
];

const mergedArray = arrays.flat(1);

console.log(mergedArray); // ["", "", "", "", "", "", ""]
Copy after login

Compatibility:

The flat() method has excellent compatibility across most environments. However, it is not supported in Node.js versions below 11 and is not supported at all in Internet Explorer.

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

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