js 实现降序
数组降序排序
在JavaScript中,可以使用数组的sort()方法实现降序排序。默认情况下,sort()方法将元素转换为字符串并按升序排列。要实现降序排序,需传入一个比较函数。
const arr = [5, 2, 9, 1, 5];
arr.sort((a, b) => b - a);
console.log(arr); // 输出: [9, 5, 5, 2, 1]
对象数组按属性降序
若需对对象数组按特定属性降序排序,同样在比较函数中处理。
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];
users.sort((a, b) => b.age - a.age);
console.log(users);
// 输出: [{name: 'Bob', age: 30}, {name: 'Alice', age: 25}, {name: 'Charlie', age: 20}]
字符串数组降序
对字符串数组降序排序时,使用localeCompare()方法或直接比较字符编码。
const fruits = ['banana', 'apple', 'cherry'];
fruits.sort((a, b) => b.localeCompare(a));
console.log(fruits); // 输出: ['cherry', 'banana', 'apple']
多条件降序排序
当需要按多个条件降序排序时,可在比较函数中依次判断。
const items = [
{ name: 'item1', price: 10, rating: 4 },
{ name: 'item2', price: 10, rating: 3 },
{ name: 'item3', price: 15, rating: 4 }
];
items.sort((a, b) => {
if (b.price !== a.price) return b.price - a.price;
return b.rating - a.rating;
});
console.log(items);
// 输出: [
// {name: 'item3', price: 15, rating: 4},
// {name: 'item1', price: 10, rating: 4},
// {name: 'item2', price: 10, rating: 3}
// ]
注意事项
-
sort()方法会直接修改原数组,若需保留原数组,可先创建副本:const original = [3, 1, 4]; const sorted = [...original].sort((a, b) => b - a); -
对于大数组或复杂排序,考虑性能优化方案,如使用
Intl.Collator或Web Worker。






