search

Home  >  Q&A  >  body text

Merge/flatten an array of arrays

<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粉828463673P粉828463673463 days ago539

reply all(2)I'll reply

  • P粉557957970

    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]

    reply
    0
  • P粉293341969

    P粉2933419692023-08-28 09:31:51


    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);
        

    reply
    0
  • Cancelreply