JavaScript Array flat() (陣列扁平化)

陣列 (array) 的 flat() 方法用來將巢狀的陣列「攤平」成一維陣列。

語法:

const newArray = arr.flat([depth]);
  • depth 是指定要攤平的深度,預設是 1

基本用法

const arr = [1, 2, [3, 4]];

arr.flat();
// [1, 2, 3, 4]

指定攤平深度

const arr = [1, [2, [3, [4]]]];

arr.flat(1); // [1, 2, [3, [4]]]
arr.flat(2); // [1, 2, 3, [4]]
arr.flat(3); // [1, 2, 3, 4]

完全攤平

使用 Infinity 可以攤平任意深度的巢狀陣列:

const arr = [1, [2, [3, [4, [5]]]]];

arr.flat(Infinity);
// [1, 2, 3, 4, 5]

移除陣列中的空項目

flat() 會移除陣列中的空項目 (empty slots):

const arr = [1, 2, , 4, 5];

arr.flat();
// [1, 2, 4, 5]

實際應用

// 合併多個使用者的訂單
const usersOrders = [
  [{ id: 1, item: 'Book' }],
  [
    { id: 2, item: 'Pen' },
    { id: 3, item: 'Notebook' },
  ],
  [{ id: 4, item: 'Pencil' }],
];

const allOrders = usersOrders.flat();
// [{ id: 1, item: 'Book' }, { id: 2, item: 'Pen' }, { id: 3, item: 'Notebook' }, { id: 4, item: 'Pencil' }]

flatMap()

flatMap() 是 map() 和 flat(1) 的結合,先對每個元素執行 map,然後將結果攤平一層:

const sentences = ['Hello World', 'How are you'];

// 用 map 會得到巢狀陣列
sentences.map(function (s) {
  return s.split(' ');
});
// [['Hello', 'World'], ['How', 'are', 'you']]

// 用 flatMap 會自動攤平
sentences.flatMap(function (s) {
  return s.split(' ');
});
// ['Hello', 'World', 'How', 'are', 'you']

另一個 flatMap 範例:

const numbers = [1, 2, 3];

numbers.flatMap(function (n) {
  return [n, n * 2];
});
// [1, 2, 2, 4, 3, 6]
flat() 和 flatMap() 是 ES2019 新增的方法。flatMap() 只會攤平一層,無法指定深度。