Home >Web Front-end >JS Tutorial >How Can I Flatten 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:
["", "", "", ...]
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!