实现js sort


实现 JavaScript 的 sort 方法
JavaScript 的 sort 方法用于对数组元素进行排序。默认情况下,sort 将元素转换为字符串并按照 Unicode 编码顺序排序。如果需要自定义排序逻辑,可以传入一个比较函数。
基本语法
array.sort([compareFunction])
默认排序(按 Unicode 编码)
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'grape', 'orange']
自定义排序(数字升序)
const numbers = [10, 5, 8, 1, 7];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 7, 8, 10]
自定义排序(数字降序)
const numbers = [10, 5, 8, 1, 7];
numbers.sort((a, b) => b - a);
console.log(numbers); // [10, 8, 7, 5, 1]
对象数组排序(按属性值)
const users = [
{ name: 'John', age: 25 },
{ name: 'Alice', 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: 'Alice', age: 30 }
// ]
字符串排序(忽略大小写)
const words = ['Apple', 'banana', 'Cherry', 'date'];
words.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(words); // ['Apple', 'banana', 'Cherry', 'date']
注意事项
sort方法会直接修改原数组,而不是返回一个新数组。- 比较函数应返回负数、零或正数,分别表示第一个参数应排在第二个参数之前、相同或之后。
- 对于大型数组,自定义比较函数的性能可能影响排序速度。
通过以上示例,可以根据具体需求灵活使用 sort 方法实现不同的排序逻辑。






