如何解决如何按两个不同的属性对数组进行排序?
我正在尝试用lodash对数组进行排序,其中我按两个属性进行排序。我目前的排序看起来像这样,但是没有用。
const sortedItems = orderBy(items,i => [i.Version,i.Active],['desc])
我想要排序。发件人:
[{
"Active": false,"Version": 1
},{
"Active": true,"Version": 3
},"Version": 2
},{
"Active": false,"Version": 4
},"Version": 5
},"Version": 1
}
]
并像这样进行排序..
[
{
"Active": true,"Version": 5
},{
"Active": true,"Version": 3
},{
"Active": true,"Version": 2
},{
"Active": false,"Version": 4
},{
"Active": false,"Version": 1
},"Version": 1
}
]
是否还有另一个lodash函数可以为我执行此操作,或者我需要分别使用两个函数?
解决方法
您可以使用JS数组排序方法来做到这一点。只需根据您的条件编写一个compare函数,然后在排序时在JavaScript数组sort方法中使用该函数即可。
const data = [
{
Active: false,Version: 1,},{
Active: true,Version: 3,Version: 2,{
Active: false,Version: 4,Version: 5,];
const cmp = (x,y) => {
if (x.Active === y.Active) {
return y.Version - x.Version;
}
return x.Active < y.Active ? 1 : -1;
};
const ret = data.sort(cmp);
console.log(ret);
,
var data = [{
"Active": false,"Version": 1
},{
"Active": true,"Version": 3
},"Version": 2
},{
"Active": false,"Version": 4
},"Version": 5
},"Version": 1
}
];
console.log(
data.sort((a,b) => (b.Active - a.Active || b.Version - a.Version))
);
- b-a将使它降序排列
- 如果b.Active和a.Active不相等,则会短路并优先使用Active属性
- 如果b.Active和a.Active相等,它将继续按次优版本的降序排序
您可以使用类似于普通JavaScript的方法
let not_sorted = {[]};
let sorted = not_sorted.sort(sorter);
function sorter(a,b)
{
if(a.Version>b.Version)
{
return -1;
}
else{
return 1;
}
}
它应该可以工作(您可以只更改return的值即可更改订单)
,arr.sort((a,b)=>{
if(a.Active != b.Active){
if(a.Active){
return 1
} else {
return -1
}
} else if(a.Version > b.Version){
return 1
} else {
return -1
}
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。