js实现升序排列
使用 Array.prototype.sort() 方法
JavaScript 数组的 sort() 方法默认将元素转换为字符串并按 Unicode 码点排序。为了实现升序排列,需传入比较函数:
const numbers = [3, 1, 4, 1, 5, 9];
numbers.sort((a, b) => a - b);
console.log(numbers); // 输出: [1, 1, 3, 4, 5, 9]
比较函数规则:

- 若返回值
< 0,a排在b前 - 若返回值
> 0,b排在a前 - 若返回值
= 0,顺序不变
对字符串数组排序
字符串数组可直接使用 sort() 方法实现字典序升序:
const fruits = ['banana', 'apple', 'cherry'];
fruits.sort();
console.log(fruits); // 输出: ['apple', 'banana', 'cherry']
如需忽略大小写排序:

const mixedCase = ['Banana', 'apple', 'Cherry'];
mixedCase.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
console.log(mixedCase); // 输出: ['apple', 'Banana', 'Cherry']
对象数组按属性排序
通过指定对象属性进行比较:
const users = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 20 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
// 输出: [{name:'Alice',age:20}, {name:'John',age:25}]
稳定排序的实现
ES2019 起 sort() 保证稳定性(相同值保持原始顺序)。如需兼容旧环境,可扩展排序逻辑:
const data = [
{ value: 1, index: 0 },
{ value: 1, index: 1 }
];
data.sort((a, b) => {
const diff = a.value - b.value;
return diff !== 0 ? diff : a.index - b.index;
});
性能注意事项
大规模数据排序时,V8 引擎(Chrome/Node.js)使用 TimSort 算法,时间复杂度为 O(n log n)。避免在循环中频繁调用 sort()。





