在 JavaScript 中,flatMap 是一個用於處理陣列的方法。它結合了 mapflat 方法的功能,能夠對陣列中的每個元素進行處理,並將處理結果展平為一維陣列。這在需要對陣列進行變換和展平時特別有用。

語法:

arr.flatMap(callback, thisArg)

 

  • callback: 一個函式,用於對陣列中的每個元素進行處理。
    • currentValue: 當前處理的元素。
    • index(可選):當前元素的索引。
    • array(可選):正在操作的陣列。
  • thisArg(可選):執行 callback 時作為 this 使用的對象。

特點

  • flatMap 的回傳值會被自動展平一層。
  • 它與先使用 map 再使用 flat(1) 效果相同,但執行效率更高。

 

範例

1. 基本範例

將每個元素展開為一個新陣列,並展平:

const arr = [1, 2, 3, 4];
const result = arr.flatMap(x => [x, x * 2]);
console.log(result);
// 輸出: [1, 2, 2, 4, 3, 6, 4, 8]

 

2. 過濾並展平

過濾掉奇數並展平:

const arr = [1, 2, 3, 4];
const result = arr.flatMap(x => (x % 2 === 0 ? [x] : []));
console.log(result);
// 輸出: [2, 4]

 

3. 分割字串並展平

對每個字串進行分割操作,並展平結果:

const words = ["hello world", "flatMap is great"];
const result = words.flatMap(word => word.split(" "));
console.log(result);
// 輸出: ['hello', 'world', 'flatMap', 'is', 'great']

 

4. 與 mapflat 的對比

使用 mapflat

const arr = [1, 2, 3];
const result = arr.map(x => [x, x * 2]).flat();
console.log(result);
// 輸出: [1, 2, 2, 4, 3, 6]

使用 flatMap

const arr = [1, 2, 3];
const result = arr.flatMap(x => [x, x * 2]);
console.log(result);
// 輸出: [1, 2, 2, 4, 3, 6]

注意事項

  • flatMap 只會展平一層,如果需要展平更深層次的陣列,可以使用 flat 方法並指定深度。
  • flatMap 不會改變原始陣列,它會返回一個新的陣列。

總結

flatMap 是處理巢狀結構時的強大工具,適合需要同時進行映射和展平操作的場景。