我有一个具有2个相关属性的未排序对象数组:type
和date
。
我需要对这个数组进行排序:
deposit
应该排在withdrawal
之前)以下是输入示例:
let i = [
{
date:'2017',
type:'withdrawal',
amount:-5
},
{
date:'2016',
type:'deposit',
amount:12
},
{
date:'2018',
type:'deposit',
amount:54
},
{
date:'2017',
type:'deposit',
amount:20
},
{
date:'2016',
type:'withdrawal',
amount:55
},
{
date:'2018',
type:'withdrawal',
amount:54
}
]
目标是输出如下内容:
let o = [
{
date:'2016',
type:'deposit',
amount:12
},
{
date:'2016',
type:'withdrawal',
amount:55
},
{
date:'2017',
type:'deposit',
amount:20
},
{
date:'2017',
type:'withdrawal',
amount:-5
},
{
date:'2018',
type:'deposit',
amount:54
},
{
date:'2018',
type:'withdrawal',
amount:54
}
]
到目前为止,我设法使用以下方法按日期对数组进行排序:
o = i.sort((a,b)=>(a.date - b.date))
但是我找不到一种按类型对其进行排序的方法
答案 0 :(得分:3)
您可以使用如下所示的“排序”。通过使用“ localeCompare”,它将按升序对“类型”进行排序-“存款”将在“提款”之前,因为“ d”在“ w”之前
就是用这个-
i.sort((a,b) => ((+a.date) - (+b.date) || (a.type.localeCompare(b.type))))
let i = [
{
date:'2017',
type:'withdrawal',
amount:-5
},
{
date:'2016',
type:'deposit',
amount:12
},
{
date:'2018',
type:'deposit',
amount:54
},
{
date:'2017',
type:'deposit',
amount:20
},
{
date:'2016',
type:'withdrawal',
amount:55
},
{
date:'2018',
type:'withdrawal',
amount:54
}
]
i.sort((a,b) => ((+a.date) - (+b.date) || (a.type.localeCompare(b.type))))
console.log(i)
答案 1 :(得分:0)
您可以使用string#localCompare
首先根据date
对数组进行排序,然后再根据type
对数组进行排序。
let arr = [ { date:'2017', type:'withdrawal', amount:-5 }, { date:'2016', type:'deposit', amount:12 }, { date:'2018', type:'deposit', amount:54 }, { date:'2017', type:'deposit', amount:20 }, { date:'2016', type:'withdrawal', amount:55 }, { date:'2018',type:'withdrawal', amount:54 } ];
arr.sort((a,b) => a.date.localeCompare(b.date) || a.type.localeCompare(b.type));
console.log(arr);
答案 2 :(得分:0)
虽然可能不是最理想的解决方案,但我在Array.prototype.sort方法中将类型作为字符串“ a”和“ b”连接到日期上,然后基于该字符串对数组进行排序。 / p>
i.sort((a,b) => {
let aStr = `${a.date}${a.type}`;
let bStr = `${b.date}${b.type}`;
if(aStr > bStr) {
return 1;
} else if(aStr === bStr) {
return 0;
} else {
return -1;
}
});
希望有帮助!