1.数字数组排序
对于数字数组,你需要提供一个比较函数来确保按数值进行排序:
const numbers = [40, 100, 1, 5, 25];numbers.sort((a, b) => a - b);console.log(numbers); // 输出: [1, 5, 25, 40, 100]
2.字符串数组排序
对于字符串数组,sort()
方法默认行为就是按字符编码顺序排序,但你也可以提供自定义的比较函数:
const fruits = ["banana", "apple", "cherry"];fruits.sort();console.log(fruits); // 输出: ["apple", "banana", "cherry"]
3.自定义排序
按对象的某个属性排序:
const people = [{ name: "John", age: 30 },{ name: "Jane", age: 25 },{ name: "Dave", age: 35 }
];people.sort((a, b) => a.age - b.age);console.log(people);
// 输出: [
// { name: "Jane", age: 25 },
// { name: "John", age: 30 },
// { name: "Dave", age: 35 }
// ]
4.逆序排序
要实现逆序排序,只需调整比较函数的返回值:
const numbers = [40, 100, 1, 5, 25];numbers.sort((a, b) => b - a);console.log(numbers); // 输出: [100, 40, 25, 5, 1]