P粉5579579702023-08-28 10:33:02
This is a short function that uses some of the newer JavaScript array methods to flatten an n-dimensional array.
function flatten(arr) { return arr.reduce(function (flat, toFlatten) { return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); }, []); }
usage:
flatten([[1, 2, 3], [4, 5]]); // [1, 2, 3, 4, 5] flatten([[[1, [1.1]], 2, 3], [4, 5]]); // [1, 1.1, 2, 3, 4, 5]
P粉2933419692023-08-28 09:31:51
ES2019 introduces arrays. prototype.flat()
method, which you can use to flatten an array. It is compatible with most environments, although it is only available in Node.js starting with version 11 and not within Node.js. It's totally fine in Internet Explorer.
const arrays = [ [""], [""], [""], [""], [""], [""], [""] ]; const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. console.log(merge3);