js数组实现排序
数组排序方法
JavaScript数组提供了内置的sort()方法用于排序,默认按Unicode码点升序排列。对于数字排序需自定义比较函数。
基本语法:
arr.sort([compareFunction])
默认排序(字符串)
不传递比较函数时,元素会被转换为字符串并按照Unicode顺序排序:
const fruits = ['banana', 'Apple', 'orange'];
fruits.sort();
// 结果: ['Apple', 'banana', 'orange'](区分大小写)
数字升序排序
通过比较函数实现数字正确排序:
const numbers = [40, 100, 1, 5];
numbers.sort((a, b) => a - b);
// 结果: [1, 5, 40, 100]
数字降序排序
调整比较函数返回值即可:
numbers.sort((a, b) => b - a);
// 结果: [100, 40, 5, 1]
对象数组排序
根据对象属性排序需在比较函数中指定属性:
const items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 }
];
items.sort((a, b) => a.value - b.value);
实现稳定排序
V8引擎(Chrome/Node.js)在7.0+版本后,sort()已是稳定排序。对于旧环境可手动实现稳定排序:
function stableSort(arr, compare) {
const mapped = arr.map((el, i) => ({ el, i }));
mapped.sort((a, b) => compare(a.el, b.el) || a.i - b.i);
return mapped.map(({ el }) => el);
}
注意事项
-
sort()会修改原数组,如需保留原数组需先拷贝:const sorted = [...arr].sort(); -
对包含
undefined的数组,这些元素会被排到末尾。 -
比较函数应返回:

- 负数:a排在b前
- 正数:b排在a前
- 零:保持相对位置






