js sort 实现
数组排序基础方法
JavaScript 数组的 sort() 方法默认按照字符串 Unicode 码点顺序排序。直接调用时会将元素转为字符串再比较:
const arr = [10, 2, 5, 1];
arr.sort(); // 结果为 [1, 10, 2, 5]
数字升序排序
通过比较函数实现数字升序排列:
const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b);
// 结果 [1, 5, 25, 40, 100]
数字降序排序
比较函数返回 b - a 可实现降序:
const nums = [15, 3, 20, 7];
nums.sort((a, b) => b - a);
// 结果 [20, 15, 7, 3]
对象属性排序
根据对象属性值排序需要自定义比较逻辑:
const items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 }
];
items.sort((a, b) => a.value - b.value);
字符串排序
对字符串数组进行不区分大小写的排序:
const names = ['Zoey', 'amy', 'bob'];
names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
// 结果 ['amy', 'bob', 'Zoey']
稳定排序实现
ES2019 后 sort() 已经是稳定排序,相同值的元素保持原始相对顺序。如需自行实现稳定排序:
function stableSort(array, compareFn) {
const indexed = array.map((value, index) => ({ value, index }));
indexed.sort((a, b) => compareFn(a.value, b.value) || a.index - b.index);
return indexed.map(x => x.value);
}
多条件排序
通过组合比较条件实现多级排序:
const students = [
{ name: 'Alex', grade: 15, age: 10 },
{ name: 'Bob', grade: 15, age: 8 }
];
students.sort((a, b) => {
if (a.grade !== b.grade) return a.grade - b.grade;
return a.age - b.age;
});
自定义排序规则
实现非标准排序逻辑,如奇偶分组:
const customArr = [3, 1, 4, 2];
customArr.sort((a, b) => {
const aOdd = a % 2;
const bOdd = b % 2;
if (aOdd === bOdd) return a - b;
return bOdd - aOdd;
});
// 结果 [1, 3, 2, 4]
性能优化建议
对大型数组排序时,避免在比较函数中进行复杂计算。可预先计算排序依据:
const bigData = /* 大型数据集 */;
bigData.forEach(item => item.sortKey = /* 计算排序键 */);
bigData.sort((a, b) => a.sortKey - b.sortKey);






