将二维数组转成一维数组的方法有哪些?

Array.prototype.flat()

  1. function flatArr(arr) {
  2. return arr.flat();
  3. }
  4. console.log(flatArr([[1, 2, 3], [3, 4, 5]]));
  5. // [ 1, 2, 3, 3, 4, 5 ]

展开任意深度flat(Infinity)

Array.prototype.reduce()

  1. function flatArr(arr) {
  2. return arr.reduce((acc, val) => acc.concat(val), []);
  3. }
  4. console.log(flatArr([[1, 2, 3], [3, 4, 5]]));
  5. // [ 1, 2, 3, 3, 4, 5 ]

扩展练习

1260. 二维网格迁移