实现sort js
使用 Array.prototype.sort()
JavaScript 数组的 sort() 方法对数组元素进行原地排序,默认将元素转换为字符串后按 Unicode 码点排序。该方法接受一个可选比较函数。
const arr = [3, 1, 4, 1, 5, 9];
arr.sort(); // 默认排序: [1, 1, 3, 4, 5, 9]
自定义比较函数
通过提供比较函数可实现更复杂的排序逻辑。比较函数应返回:
- 负数:
a应排在b前 - 正数:
b应排在a前 - 零:顺序不变
// 数字升序
arr.sort((a, b) => a - b);
// 数字降序
arr.sort((a, b) => b - a);
// 字符串排序
const strArr = ['banana', 'apple', 'cherry'];
strArr.sort(); // 默认按字母顺序
对象数组排序
对对象数组可按特定属性排序:
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 22 }
];
// 按 age 升序
users.sort((a, b) => a.age - b.age);
// 按 name 字母顺序
users.sort((a, b) => a.name.localeCompare(b.name));
稳定排序实现
ES2019 要求 sort() 必须稳定(相同元素保持原有顺序)。如需自行实现稳定排序:
function stableSort(arr, compare) {
return arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
}
性能优化
对大型数组可考虑以下优化:
- 避免在比较函数中创建新对象
- 对同类型数据使用类型特定的比较器
- 对预排序数据使用插入排序等适应性算法
非ASCII字符排序
对含特殊字符的字符串应使用 localeCompare:

const items = ['résumé', 'apple', 'éclair'];
items.sort((a, b) => a.localeCompare(b));






