Merge/flatten an array of arrays
P粉828463673
P粉828463673 2023-08-27 12:05:43
0
2
526
<p>I have a JavaScript array, for example: </p> <pre class="brush:php;toolbar:false;">[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], [" $22"], ["$10"]]</pre> <p>How do I combine separate internal arrays into one array like this: </p> <pre class="brush:php;toolbar:false;">["$6", "$12", "$25", ...]</pre> <p><br /></p>
P粉828463673
P粉828463673

reply all(2)
P粉557957970

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粉293341969

ES2019

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);
    
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template