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

How Can I Flatten Nested Arrays in JavaScript?

Patricia Arquette
Release: 2024-12-29 00:23:09
Original
162 people have browsed it

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:

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

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

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

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); // ["", "", "", ...]
Copy after login

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!

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