js 实现sort
实现 JavaScript 的 sort 方法
JavaScript 的 Array.prototype.sort 方法用于对数组元素进行排序。默认情况下,它将元素转换为字符串并按照 Unicode 码点顺序排序。可以通过传递一个比较函数来自定义排序行为。
默认排序(按 Unicode 码点)
默认情况下,sort 方法会将数组元素转换为字符串,然后比较它们的 Unicode 码点顺序。

const fruits = ['banana', 'Apple', 'orange', 'Cherry'];
fruits.sort();
console.log(fruits); // ['Apple', 'Cherry', 'banana', 'orange']
自定义排序(使用比较函数)
通过传递一个比较函数,可以自定义排序逻辑。比较函数接收两个参数 a 和 b,并返回以下值:
- 负数:
a排在b前面 - 正数:
b排在a前面 - 零:顺序不变
const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b); // 升序排序
console.log(numbers); // [1, 5, 25, 40, 100]
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 }
// ]
字符串排序(不区分大小写)
默认的字符串排序区分大小写。可以通过转换为统一大小写来实现不区分大小写的排序。
const fruits = ['banana', 'Apple', 'orange', 'Cherry'];
fruits.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
console.log(fruits); // ['Apple', 'banana', 'Cherry', 'orange']
稳定排序
从 ES2019 开始,sort 方法是稳定的,即对于相同值的元素,排序后的相对顺序与排序前一致。
const items = [
{ name: 'Apple', weight: 1 },
{ name: 'Banana', weight: 2 },
{ name: 'Cherry', weight: 1 }
];
items.sort((a, b) => a.weight - b.weight);
console.log(items);
// [
// { name: 'Apple', weight: 1 },
// { name: 'Cherry', weight: 1 },
// { name: 'Banana', weight: 2 }
// ]
注意事项
sort方法会修改原数组。- 对于数字排序,直接使用默认排序会导致错误结果(如
[1, 10, 2, 20])。 - 复杂排序可能需要更复杂的比较函数。






