JS数组对象的正序、倒序和根据中文首字母排序

//数组对象方法排序:升序
sortByKey(array,key){
	return array.sort(function(a,b){
		var x=a[key];
		var y=b[key];
		return ((x<y)?-1:((x>y)?1:0));
	});
},
//数组对象方法排序:降序
sortDownByKey(array,key){
	return array.sort(function(a,b){
		var x=a[key];
		var y=b[key];
		return ((x>y)?-1:((x<y)?1:0));
	});
},

需要排序的数据结构

let earningsRecordList = [{
	gainId: 0,
	gainName: '猪小白',
	gainGoods: '降温床垫',
	gainStatus: '已返',
	goodsTime: 1597048710000,
	gainMoney: 240.01,
	gainTime: 1597048710000,
	orderDetail:{
		shopId:0,
		shopName:'中明珠装饰',
		goodsName:'2020最新灯饰2020最新灯饰2020最新灯饰2020最新灯饰',
		goodsType:'露珠A款-【无极调光】',
		goodsNum:2,
		goodsService:'免费上门安装',
		orderNo:'124515169452'
	}
},{
	gainId: 1,
	gainName: '猪小白',
	gainGoods: '降温床垫',
	gainStatus: '未返',
	goodsTime: 1597135110000,
	gainMoney: 104.02,
	gainTime: 1597135110000,
	orderDetail:{
		shopId:0,
		shopName:'纯明珠装饰',
		goodsName:'2020最新灯饰2020最新灯饰2020最新灯饰2020最新灯饰',
		goodsType:'露珠A款-【无极调光】',
		goodsNum:2,
		goodsService:'免费上门安装',
		orderNo:'124515169452'
	}
},{
	gainId: 2,
	gainName: '猪小白',
	gainGoods: '降温床垫',
	gainStatus: '已返',
	goodsTime: 1597221510000,
	gainMoney: 356.03,
	gainTime: 1597221510000,
	orderDetail:{
		shopId:0,
		shopName:'福明珠装饰',
		goodsName:'2020最新灯饰2020最新灯饰2020最新灯饰2020最新灯饰',
		goodsType:'露珠A款-【无极调光】',
		goodsNum:2,
		goodsService:'免费上门安装',
		orderNo:'124515169452'
	}
},{
	gainId: 3,
	gainName: '猪小白',
	gainGoods: '降温床垫',
	gainStatus: '已返',
	goodsTime: 1597307910000,
	gainMoney: 333.04,
	gainTime: 1597307910000,
	orderDetail:{
		shopId:0,
		shopName:'啊明珠装饰',
		goodsName:'2020最新灯饰2020最新灯饰2020最新灯饰2020最新灯饰',
		goodsType:'露珠A款-【无极调光】',
		goodsNum:2,
		goodsService:'免费上门安装',
		orderNo:'124515169452'
	}
},{
	gainId: 4,
	gainName: '猪小白',
	gainGoods: '降温床垫',
	gainStatus: '未返',
	goodsTime: 1597394310000,
	gainMoney: 854.05,
	gainTime: 1597394310000,
	orderDetail:{
		shopId:0,
		shopName:'可明珠装饰',
		goodsName:'2020最新灯饰2020最新灯饰2020最新灯饰2020最新灯饰',
		goodsType:'露珠A款-【无极调光】',
		goodsNum:2,
		goodsService:'免费上门安装',
		orderNo:'124515169452'
	}
}]

中文首字符的降序排列

this.earningsRecordList.sort((a, b) => {
	return b.orderDetail.shopName.localeCompare(a.orderDetail.shopName, 'zh-Hans-CN');
})

中文首字符的升序排列

this.earningsRecordList.sort((a, b) => {
	return a.orderDetail.shopName.localeCompare(b.orderDetail.shopName, 'zh-Hans-CN');
})

按照gainMoney降序排列

this.sortDownByKey(this.earningsRecordList,'gainMoney');

按照gainMoney升序排列

this.sortByKey(this.earningsRecordList,'gainMoney');

Tips:
关于按照中文排序的.localeCompare()方法,W3school这样解释:
在这里插入图片描述
官网相关链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值