基本排序:單一欄位
$.getJSON('/api/users', function(users) {
// 依 name 升冪排序
users.sort((a, b) => a.name.localeCompare(b.name));
users.forEach(user => {
console.log(user.name);
});
});
數值欄位排序
// 年齡升冪
users.sort((a, b) => a.age - b.age);
// 年齡降冪
users.sort((a, b) => b.age - a.age);
多欄位排序(複合鍵)
// 先按 department 升冊,再按 age 降冊
users.sort((a, b) => {
const deptCmp = a.department.localeCompare(b.department);
if (deptCmp !== 0) return deptCmp;
return b.age - a.age; // 同部門內,年齡大者優先
});
通用多鍵排序工具函數
function createMultiKeySorter(keys) {
// keys: [{key: 'field', dir: 'asc'|'desc', type: 'string'|'number'|'date'}, ...]
return (a, b) => {
for (const {key, dir = 'asc', type = 'string'} of keys) {
let valA = a[key], valB = b[key];
// 型別轉換
if (type === 'number') { valA = Number(valA); valB = Number(valB); }
else if (type === 'date') { valA = new Date(valA); valB = new Date(valB); }
let cmp = 0;
if (valA < valB) cmp = -1;
else if (valA > valB) cmp = 1;
if (cmp !== 0) return dir === 'asc' ? cmp : -cmp;
}
return 0;
};
}
// 使用
const sorter = createMultiKeySorter([
{key: 'department', dir: 'asc', type: 'string'},
{key: 'hireDate', dir: 'desc', type: 'date'},
{key: 'salary', dir: 'desc', type: 'number'}
]);
users.sort(sorter);
處理 null/undefined 值
users.sort((a, b) => {
const va = a.optionalField, vb = b.optionalField;
if (va == null && vb == null) return 0;
if (va == null) return 1; // null 置後
if (vb == null) return -1;
return va.localeCompare(vb);
});
效能優化:預計算排序鍵
// 大量資料時,預先計算排序鍵避免重複存取/轉換
const enriched = users.map(u => ({
...u,
_sortKey: u.department + '\0' + (999 - u.age).toString().padStart(5, '0')
}));
enriched.sort((a, b) => a._sortKey.localeCompare(b._sortKey));
// 移除輔助鍵
enriched.forEach(u => delete u._sortKey);
現代原生替代(無 jQuery 依賴)
fetch('/api/users')
.then(r => r.json())
.then(users => {
users.sort((a, b) => a.name.localeCompare(b.name));
// 渲染...
});
總結
- 字串用 `localeCompare()`(支援多語言、數字感知)
- 數值用減法 `a - b`(升冊)或 `b - a`(降冊)
- 多欄位按優先序串聯比較,優先欄位相等才比較次級欄位
- 大量資料考慮預計算排序鍵或 Web Worker 離線排序
- jQuery `$.getJSON` 只是簡便 AJAX,排序邏輯純屬原生 JS