js实现sort
实现 JavaScript 的 sort 方法
JavaScript 的 Array.prototype.sort 方法用于对数组元素进行排序。默认情况下,它将元素转换为字符串并按 Unicode 码点排序。要实现自定义排序,可以传入比较函数。
默认排序(按 Unicode 码点)
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'grape', 'orange']
自定义排序(数字升序)
const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 25, 40, 100]
自定义排序(数字降序)
const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => b - a);
console.log(numbers); // [100, 40, 25, 5, 1]
对象数组排序(按属性值)
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 20 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
// [
// { name: 'Bob', age: 20 },
// { name: 'John', age: 25 },
// { name: 'Jane', age: 30 }
// ]
实现稳定排序
JavaScript 的 sort 方法在某些浏览器中可能不稳定(相同元素的相对顺序可能改变)。要实现稳定排序,可以扩展比较逻辑:
function stableSort(array, compare) {
const indexedArray = array.map((value, index) => ({ value, index }));
indexedArray.sort((a, b) => compare(a.value, b.value) || a.index - b.index);
return indexedArray.map(item => item.value);
}
const data = [
{ name: 'A', priority: 1 },
{ name: 'B', priority: 2 },
{ name: 'C', priority: 1 }
];
const result = stableSort(data, (a, b) => a.priority - b.priority);
console.log(result);
// [
// { name: 'A', priority: 1 },
// { name: 'C', priority: 1 },
// { name: 'B', priority: 2 }
// ]
本地化字符串排序
对于需要考虑语言特性的字符串排序,使用 localeCompare:

const names = ['Ångström', 'Zebra', 'äpple', 'Apple'];
names.sort((a, b) => a.localeCompare(b, 'sv'));
console.log(names); // ['Apple', 'äpple', 'Ångström', 'Zebra']
注意事项
sort方法会修改原数组- 比较函数应返回负数、零或正数
- 对于大型数组,考虑性能优化(如避免在比较函数中进行复杂计算)






