Home >Web Front-end >JS Tutorial >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!