Array.prototype.filter()(通常簡稱 Array.filter())是 JavaScript 用來篩選陣列的內建方法:你給它一個判斷函式,它回傳一個只包含「通過判斷」元素的新陣列。
白話一點,就像網購時勾選「有現貨」的篩選條件:商品清單本身沒變,你只是得到一份符合條件的新清單。
語法與回傳值
arr.filter(callbackFn)
arr.filter(callbackFn, thisArg)
| 項目 | 說明 |
|---|---|
callbackFn | 對每個元素執行的函式;回傳真值(truthy)就保留該元素,回傳假值(falsy)就排除 |
| 回呼的三個參數 | element(目前元素)、index(索引)、array(呼叫 filter() 的那個陣列) |
thisArg | 選填,執行 callbackFn 時當作 this 的值 |
| 回傳值 | 通過判斷的元素組成的淺層拷貝(shallow copy)新陣列;沒有任何元素通過時回傳空陣列 [] |
以上依 MDN 的 Array.prototype.filter() 頁面整理。
基本用法:篩選數字
const nums = [12, 5, 8, 130, 44];
const big = nums.filter((n) => n >= 10);
console.log(big); // [ 12, 130, 44 ]
console.log(nums); // [ 12, 5, 8, 130, 44 ](原陣列沒有被改動)
filter() 不會修改原陣列,所以 nums 仍是原本的五個元素。
如果沒有任何元素通過,回傳的是空陣列,不是 undefined,後面可以直接接 .length 或 .map():
console.log(nums.filter((n) => n > 1000)); // []
篩選物件陣列
實務上最常見的是篩選 API 回傳的物件陣列。多個條件用 &&(且)或 ||(或)組合:
const products = [
{ name: '機械鍵盤', price: 2400, inStock: true },
{ name: '無線滑鼠', price: 850, inStock: false },
{ name: '滑鼠墊', price: 300, inStock: true },
];
const result = products.filter((p) => p.inStock && p.price < 1000);
console.log(result);
// [ { name: '滑鼠墊', price: 300, inStock: true } ]
字串搜尋可以搭配 includes(),下例改成不分大小寫:
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
console.log(fruits.filter((el) => el.toLowerCase().includes('ap')));
// [ 'apple', 'grapes' ]
用索引參數去除重複值
回呼的第二、第三個參數可以拿來比對位置。下面的寫法只保留每個值第一次出現的位置:
const dup = ['a', 'b', 'a', 'c', 'b'];
const unique = dup.filter((v, i, arr) => arr.indexOf(v) === i);
console.log(unique); // [ 'a', 'b', 'c' ]
filter(Boolean) 會一併排除 0 與空字串
把 Boolean 當作回呼,就是保留所有真值的元素:
const mixed = [0, 1, '', 'a', null, undefined, NaN, false, 7];
console.log(mixed.filter(Boolean)); // [ 1, 'a', 7 ]
要留意 0、''、false 也是假值,會一起被排除。如果只想去掉 null 和 undefined,要明確寫出條件:
const noNullish = mixed.filter((v) => v !== null && v !== undefined);
// 結果保留 0、1、''、'a'、NaN、false、7
清除 null 的完整寫法,可以看 JS 去除 array 中 null 或空值。
注意事項
- 回傳的是淺層拷貝:陣列是新的,但裡面的物件仍是同一份參照。修改篩選結果裡的物件,原陣列的物件也會跟著變:
const inStock = products.filter((p) => p.inStock);
inStock[0].price = 1;
console.log(products[0].price); // 1
console.log(inStock[0] === products[0]); // true
- 回呼必須是函式:漏傳回呼會丟出
TypeError(Node.js v22 的訊息是undefined is not a function)。ECMAScript 規格也規定callback不是可呼叫(callable)時要丟出TypeError。 - 不會處理空位:稀疏陣列(sparse array)的空位不會呼叫回呼,也不會出現在結果裡:
console.log([1, , undefined].filter((x) => x === undefined)); // [ undefined ]
console.log([1, , undefined].filter((x) => x !== 2)); // [ 1, undefined ]
- 處理範圍在開始時就決定:ECMAScript 規格說明,
filter處理的元素範圍在第一次呼叫回呼之前就設定好了,呼叫開始後才追加進陣列的元素不會被走訪。
常見搭配
filter() 回傳的是陣列,所以可以直接串接其他陣列方法,例如先篩選偶數、再乘以 10:
const nums2 = [1, 2, 3, 4, 5, 6];
console.log(nums2.filter((n) => n % 2 === 0).map((n) => n * 10));
// [ 20, 40, 60 ]
如果篩選後要加總,可以接 JS 陣列加總與平均值:Array.reduce。
發佈留言