搜尋

首頁  >  問答  >  主體

合併/展平數組的數組

<p>我有一個 JavaScript 數組,例如:</p> <pre class="brush:php;toolbar:false;">[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], [" $22"], ["$10"]]</pre> <p>我如何將單獨的內部數組合併成一個這樣的陣列:</p> <pre class="brush:php;toolbar:false;">["$6", "$12", "$25", ...]</pre> <p><br /></p>
P粉828463673P粉828463673563 天前643

全部回覆(2)我來回復

  • P粉557957970

    P粉5579579702023-08-28 10:33:02

    這是一個簡短的函數,它使用一些較新的 JavaScript 陣列方法來展平 n 維數組。

    function flatten(arr) {
      return arr.reduce(function (flat, toFlatten) {
        return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
      }, []);
    }

    用法:

    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]

    回覆
    0
  • P粉293341969

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


    ES2019

    ES2019 引進了陣列。 prototype.flat() 方法,您可以使用它來展平陣列。它與大多數環境相容,儘管它僅在從版本 11 開始的 Node.js 中可用,而不是在 Node.js 中可用。在 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);
        

    回覆
    0
  • 取消回覆