I have an unsorted array of object having 2 revelant property: type
, and date
. I need to sort this array:
deposit
should go first before withdrawal
) Here is an example of input:
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
}
]
The goal is to output something like this:
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
}
]
So far I managed to sort the array by date using:
o = i.sort((a,b)=>(a.date - b.date))
But I can't find a way to sort it by type
You can use "sort" like below. By using "localeCompare" it will sort "type" in increasing order - which is "deposit" will come before "withdrawl" as "d" comes before "w"
That is use this -
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)
You can use string#localCompare
to sort the array first based on date
and then on 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);
While probably not the most optimal solution, I concat'ed the type onto the date as a string for both "a" and "b" in the Array.prototype.sort method, and sorted the array based on that.
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;
}
});
Hope that helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.