数组的排序

js中常用的数组排序业务主要为简单数组排序与对象数组排序。
这里主要适用的是 sort() 方法:

说明:

  1. 若调用该方法时未使用参数,将按字符编码顺序对数组中元素进行排序。
  2. 若调用该方法时使用参数 sort(a, b),则比较a和b两个值(默认 a < b),然后返回用于说明两个值的相对顺序的数字。返回值如下:
  1. 返回值 < 0
  2. 返回值 = 0
  3. 返回值 > 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')));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值