Problem:
You have a JavaScript array containing an array of inner arrays, such as:
[ [ "" ], [ "" ], [ "" ], [ "" ], [ "" ], [ "" ], [ "" ] ]
and you want to merge them into a single, flattened array:
[ "", "", "", ... ]
Solution:
ES2019 Array.prototype.flat() Method:
ES2019 introduced the Array.prototype.flat() method, which provides a simple and concise way to flatten an array of arrays. It is compatible with most modern environments, including Node.js version 11 and above, but it is not supported in Internet Explorer.
const arrays = [ [""], [""], [""], [""], [""], [""], [""] ]; const mergedArray = arrays.flat(); console.log(mergedArray); // Logs: [ "", "", "", "", "", "", "" ]
The flat() method can also take a depth parameter, which specifies how deep the nested array structure should be flattened. By default, it is set to 1, meaning it will flatten one level of nested arrays. To flatten all levels, you can pass Infinity as the depth parameter.
The above is the detailed content of How Can I Flatten a Nested Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!