const arr = [1, 2, 11, 3434, 3, 4545, 33, 55, 0];
arr.sort(); // ["0", "1", "11", "2", "3", "33", "3434", "4545", "55"] — 字典序!
Array.prototype.sort() 預設將元素轉字串比較,數值排序**必須提供比較函式**。
// 升序
arr.sort((a, b) => a - b);
// 降序
arr.sort((a, b) => b - a);
const people = [
{ name: 'Zhang1', age: 11 },
{ name: 'Zhang2', age: 1 },
{ name: 'Zhang3', age: 18 },
{ name: 'Zhang4', age: 13 }
];
// 按 age 升序
people.sort((a, b) => a.age - b.age);
// 按 name 字典序
people.sort((a, b) => a.name.localeCompare(b.name));
/**
* 建立多屬性排序比較函式
* @param {...string} props - 屬性名,前綴 '-' 表示降序,如 '-age', 'name'
* @returns {(a,b)=>number} 比較函式
*/
function createMultiSort(...props) {
const parsers = props.map(prop => {
const desc = prop.startsWith('-');
const key = desc ? prop.slice(1) : prop;
return { key, desc };
});
return (a, b) => {
for (const { key, desc } of parsers) {
const va = a[key];
const vb = b[key];
if (va === vb) continue;
// 處理 null/undefined 排最後
if (va == null && vb == null) continue;
if (va == null) return 1;
if (vb == null) return -1;
// 數值比較
if (typeof va === 'number' && typeof vb === 'number') {
return desc ? vb - va : va - vb;
}
// 字串比較(支援中文)
return desc ? String(vb).localeCompare(String(va)) : String(va).localeCompare(String(vb));
}
return 0;
};
}
// 使用範例
const data = [
{ id: 1, name: 'Alice', age: 25, score: 90 },
{ id: 2, name: 'Bob', age: 30, score: 85 },
{ id: 3, name: 'Alice', age: 20, score: 95 },
{ id: 4, name: 'Charlie', age: 25, score: 90 }
];
// 先按 name 升序,再按 age 降序,最後按 score 升序
data.sort(createMultiSort('name', '-age', 'score'));
/* 結果:
1. Alice (age 25, score 90)
2. Alice (age 20, score 95) ← 同名年齡大者優先
3. Bob (age 30, score 85)
4. Charlie (age 25, score 90)
*/
function createSort(config) {
// config: [{ key: 'age', desc: false, cmp: (a,b)=>... }, ...]
return (a, b) => {
for (const { key, desc = false, cmp } of config) {
const va = a[key], vb = b[key];
if (va === vb) continue;
let res = cmp ? cmp(va, vb) : (va < vb ? -1 : 1);
if (desc) res = -res;
if (res !== 0) return res;
}
return 0;
};
}
// 使用自定義比較:score 依「及格 60 分為界」分組排序
data.sort(createSort([
{ key: 'score', cmp: (a, b) => (a >= 60) === (b >= 60) ? a - b : (a >= 60 ? -1 : 1) },
{ key: 'name' }
]));
sort() **原地修改**原陣列並回傳同一參考。需保留原序時請先拷貝:[...arr].sort(...)。sort() 穩定,現代瀏覽器皆已遵循。| 需求 | 比較函式 |
|---|---|
| 數值升序 | (a,b)=>a-b |
| 數值降序 | (a,b)=>b-a |
| 字串升序(含中文) | (a,b)=>a.localeCompare(b) |
| 字串降序 | (a,b)=>b.localeCompare(a) |
| 日期升序 | (a,b)=>new Date(a)-new Date(b) |
| 布林值 false 優先 | (a,b)=>a===b?0:a?1:-1 |
| null/undefined 最後 | (a,b)=>a==null?1:b==null?-1:0 (再接實際比較) |
掌握比較函式的撰寫技巧,就能應對任何複雜的陣列排序需求,不再受限於單一屬性或固定順序。