js中常用的数组排序业务主要为简单数组排序与对象数组排序。
这里主要适用的是 sort() 方法:
说明:
- 若调用该方法时未使用参数,将按字符编码顺序对数组中元素进行排序。
- 若调用该方法时使用参数 sort(a, b),则比较a和b两个值(默认 a < b),然后返回用于说明两个值的相对顺序的数字。返回值如下:
- 返回值 < 0
- 返回值 = 0
- 返回值 > 0
简单数组排序
const arr = [1,6,3,5,7,8,5,11,45,22];
// 从小到大
const asceOrder = (arr) => arr.sort((a,b) => a - b);
console.log(asceOrder(arr)); // [1, 3, 5, 5, 6, 7, 8, 11, 22, 45]
// 从大到小
const descOrder = (arr) => arr.sort((a,b) => b - a);
console.log(descOrder(arr)); // [45, 22, 11, 8, 7, 6, 5, 5, 3, 1]
对象数组排序
const arr = [
{ id: 3, name: '元素3' },
{ id: 1, name: '元素1' },
{ id: 6, name: '元素6' },
{ id: 4, name: '元素4' },
{ id: 5, name: '元素5' },
{ id: 2, name: '元素2' }
];
// 升序
const sortByPropAsce = (prop) => {
return (a, b) => {
return a[prop] - b[prop]
}
}
console.log(arr.sort(sortByPropAsce('id')));
// 降序
const sortByPropDesc = (prop) => {
return (a, b) => {
return b[prop] - a[prop]
}
}
console.log(arr.sort(sortByPropDesc('id')));