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
Barbara StreisandOriginal
2024-12-31 06:23:13267browse

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:

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

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

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

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); // ["", "", "", "", "", "", ""]

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:
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