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

How Can I Flatten Nested Arrays in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 00:23:09143browse

How Can I Flatten Nested Arrays in JavaScript?

Methods to Merge Nested Arrays in JavaScript

Problem Statement:

JavaScript arrays can sometimes contain nested arrays. The goal is to flatten these nested arrays to create a single, unidimensional array. For example, given an array like:

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

we aim to merge the inner arrays into a single array:

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

Solution in ES2019 and Node.js >= v11

ES2019:

ES2019 provides the Array.prototype.flat() method to flatten nested arrays. It takes an optional parameter specifying the depth level of flattening. By default, it flattens one level deep.

const arrays = [
  [""],
  [""],
  [""],
  [""],
  [""],
  [""],
  [""]
];
const merge3 = arrays.flat(1); // The depth level to flatten (defaults to 1)
console.log(merge3); // ["", "", "", ...]

The above is the detailed content of How Can I Flatten Nested Arrays 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