Array.prototype.sort() 就地排序陣列並回傳同一陣列參考。預設按 Unicode 碼點排序(字串比較),數值排序需提供比較函式。
array.sort([compareFunction])
a 排在 b 前面。b 排在 a 前面。const nums = [3600, 5010, 10100, 801];
// 升冪
nums.sort((a, b) => a - b); // [801, 3600, 5010, 10100]
// 降冪
nums.sort((a, b) => b - a); // [10100, 5010, 3600, 801]
const fruits = ['Apple', 'Banana', 'Orange'];
fruits.sort((a, b) => a.localeCompare(b)); // 依語系正確排序
const employees = [
{ name: 'George', age: 32 },
{ name: 'Edward', age: 17 },
{ name: 'Christine', age: 58 }
];
// 依 age 升冪
employees.sort((a, b) => a.age - b.age);
const by = (key, minor) => (a, b) => {
if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1;
return minor ? minor(a, b) : 0;
};
employees.sort(by('age', by('name')));
Intl.Collator 快取比較器。slice() 複製。掌握 sort() 比較函式撰寫技巧,配合箭頭函式與高階函式 by(),即能優雅處理各類複雜排序需求。