Array.prototype.sort() 是 JS 最常用的排序方法,但默認按 Unicode 字符串排序導致數字排序錯誤。本文系統講解比較函數編寫、數字/日期/對象/多字段排序、穩定排序保證、性能特徵與常見陷阱。
[2, 4, 8, 1, 22, 3].sort();
// [1, 2, 22, 3, 4, 8] — "22" < "3" (字符 '2' < '3')
arr.sort(function compare(a, b) {
// 返回 < 0 : a 排在 b 前
// 返回 = 0 : 相對位置不變(穩定排序保證)
// 返回 > 0 : b 排在 a 前
});
| 場景 | 比較函數 | 示例結果 |
|---|---|---|
| 數字升序 | (a,b)=>a-b | [1,2,3,4,8,22] |
| 數字降序 | (a,b)=>b-a | [22,8,4,3,2,1] |
| 日期升序 | (a,b)=>a.getTime()-b.getTime() 或 a-b | 早→晚 |
| 字符串本地化排序 | (a,b)=>a.localeCompare(b, 'zh-CN') | 拼音/筆畫序 |
| 對象按字段升序 | (a,b)=>a.field - b.field | 數字字段 |
| 對象按字段降序 | (a,b)=>b.field - a.field | — |
| 多字段:age↑, name↓ | (a,b)=>a.age-b.age || b.name.localeCompare(a.name) | 短路特性組合 |
| 空值/undefined 置後 | (a,b)=> (a==null)-(b==null) || a-b | null 最後 |
var arr = [2,4,8,1,22,3];
var sorted = arr.slice().sort((a,b) => a - b); // 不改動原數組
console.log(sorted); // [1,2,3,4,8,22]
console.log(arr); // [2,4,8,1,22,3] 原數組不變
var products = [
{name:'Apple', price:10, category:'Fruit'},
{name:'Banana', price:5, category:'Fruit'},
{name:'Carrot', price:3, category:'Vegetable'}
];
// 類別升序,同類別價格降序
products.sort((a,b) =>
a.category.localeCompare(b.category) || b.price - a.price
);
var dates = ['2024-01-15', '2023-12-01', '2024-01-10'];
dates.sort((a,b) => new Date(a) - new Date(b)); // ISO 字符串可直接相減
規範要求 sort 穩定:相等元素相對順序不變。現代瀏覽器(Chrome 70+, Firefox 60+, Safari 12+, Edge 79+)均已實現。舊環境需引入 Polyfill 或使用穩定排序庫。
return 比較函數 → 返回 undefined → 行為未定義。true/false → 隱式轉 1/0,邏輯錯誤。slice() 或 [...arr] 複製。(a?.field ?? 0) - (b?.field ?? 0)。type Comparator = (a: T, b: T) => number;
function byField(field: keyof T, dir: 'asc'|'desc' = 'asc'): Comparator {
return (a, b) => {
const av = a[field], bv = b[field];
return dir === 'asc' ? (av > bv ? 1 : av < bv ? -1 : 0)
: (av < bv ? 1 : av > bv ? -1 : 0);
};
}
users.sort(byField('age', 'asc')); // 類型安全
掌握 sort(compareFn) 靈活組合比較邏輯,是處理列表展示、數據分析、表格排序的核心技能。