我需要使用 JS 的 flat 方法展平一个多维数组。这是数组 [ ["1", "0"], ["3", "5", ["8", ["10"], "11"] ], ]

I need to flatten a multi dimensional array using JS 's flat method. This is the Array [ ["1", "0"], ["3", "5", ["8", ["10"], "11"] ], ]

function flatArrs(arr) {
  let output = arr
    .flat()
    .sort((a, b) => a - b);
  console.log(output);
}

flatArrs([
  ["1", "0"],
  ["3", "5", ["8", ["10"], "11"]],
]);

这是输出,所有数组都没有显示为扁平化...为什么? [ '0', '1', '3', '5', [ '8', [ '10' ], '11' ] ]

flat() takes a depth parameter which specifies how deep to flatten, the default is 1. To flatten to an arbitrary depth you can pass Infinity.

MDN 详细介绍了一些 alternatives,包括使用 concat()、递归和生成器函数。

function flatArrs(arr) {
  let output = arr
    .flat(Infinity)
    .sort((a, b) => a - b);
  console.log(output);
}

flatArrs([
  ["1", "0"],
  ["3", "5", ["8", ["10"], "11"]],
]);