js实现升序排列
使用 sort() 方法进行升序排列
JavaScript 数组的 sort() 方法默认按 Unicode 码点排序,因此直接使用可能无法正确对数字排序。需传入比较函数实现升序排列。
const numbers = [3, 1, 4, 1, 5, 9, 2, 6];
numbers.sort((a, b) => a - b);
console.log(numbers); // 输出: [1, 1, 2, 3, 4, 5, 6, 9]
对字符串数组进行升序排列
字符串数组可直接使用 sort() 方法,默认按字母顺序升序排列。
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // 输出: ['apple', 'banana', 'grape', 'orange']
对对象数组按属性升序排列
若需根据对象属性排序,需在比较函数中指定属性值。
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 21 },
{ name: 'Charlie', age: 23 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
// 输出: [{name: 'Bob', age: 21}, {name: 'Charlie', age: 23}, {name: 'Alice', age: 25}]
保持原数组不变的排序方式
sort() 会修改原数组。若需保留原数组,可先复制数组再排序。
const original = [5, 2, 9, 1];
const sorted = [...original].sort((a, b) => a - b);
console.log(original); // [5, 2, 9, 1]
console.log(sorted); // [1, 2, 5, 9]
处理特殊字符的字符串排序
包含大小写或特殊字符时,可使用 localeCompare 实现更精确的排序。

const mixed = ['ä', 'a', 'A', 'b'];
mixed.sort((a, b) => a.localeCompare(b));
console.log(mixed); // 输出: ['a', 'A', 'ä', 'b']






