1.升序(比较两个数)
const numbers = [4, 2, 5, 1, 3];
numbers.sort(function (a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
// 或者
const numbers2 = [4, 2, 5, 1, 3];
numbers2.sort((a, b) => a - b);
console.log(numbers2);
// [1, 2, 3, 4, 5]
2.根据对象的属性排序。
const arr = [
{ id: '001', name: '马冬梅', age: 21, sex: '女' },
{ id: '002', name: '周冬雨', age: 20, sex: '女' },
{ id: '003', name: '周杰伦', age: 23, sex: '男' },
{ id: '004', name: '温兆伦', age: 22, sex: '男' },
]
const ageArr = arr.sort((p1, p2) => p1.age - p2.age)//根据年龄升序排序
console.log(ageArr);
标签:sort,const,降序,sex,age,升序,id From: https://www.cnblogs.com/suquanxing/p/17061461.html