sort js实现
sort js实现
在JavaScript中,数组的排序可以通过Array.prototype.sort()方法实现。该方法默认将元素转换为字符串并按照Unicode码点排序,但也可以接受自定义比较函数以实现更复杂的排序逻辑。
基本用法
默认情况下,sort()方法会将数组元素转换为字符串后排序:
const fruits = ['banana', 'apple', 'orange'];
fruits.sort(); // ['apple', 'banana', 'orange']
对于数字数组,直接使用sort()会得到错误结果(按字符串比较):
const numbers = [10, 2, 5];
numbers.sort(); // [10, 2, 5](错误结果)
自定义比较函数
通过传递比较函数,可以实现数字或其他复杂类型的正确排序:
const numbers = [10, 2, 5];
numbers.sort((a, b) => a - b); // [2, 5, 10](升序)
numbers.sort((a, b) => b - a); // [10, 5, 2](降序)
对象数组排序
对对象数组排序时,需在比较函数中指定属性:
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];
users.sort((a, b) => a.age - b.age); // 按年龄升序
多条件排序
通过扩展比较函数逻辑,可以实现多条件排序:

const items = [
{ name: 'apple', price: 10, weight: 1 },
{ name: 'orange', price: 15, weight: 2 },
{ name: 'banana', price: 10, weight: 3 }
];
items.sort((a, b) => {
if (a.price !== b.price) return a.price - b.price;
return a.weight - b.weight;
}); // 先按价格升序,价格相同则按重量升序
注意事项
sort()会修改原数组,如需保留原数组需先拷贝:const original = [3, 1, 2]; const sorted = [...original].sort();- 对中文排序需使用
localeCompare:const names = ['张三', '李四', '王五']; names.sort((a, b) => a.localeCompare(b, 'zh')); - 大数组排序可能涉及性能问题,需考虑算法优化或分批处理。






