let be this object:
{
type: string,
date: Date
}
I have an array of objects as above and I want to sort it to get first items that have 'Premium' as type and then list all the others, ordered by date.
How to accomplish to this with sort
method of Javascript?
Use a custom sort function and add some hard constraints. Could have some minor issues, but shoud be ok for the most part
let obj = [{ type: 'Premium', date: new Date('1995-12-17T03:24:00') }, { type: 'random', date: new Date('1995-12-17T03:24:00') }, { type: 'Premium', date: new Date('1995-12-17T03:22:00') }, { type: 'random', date: new Date('1995-12-17T03:21:00') }, { type: 'random', date: new Date('1995-12-17T03:20:00') }] let obj2 = obj.sort((x, y) => { if(x.type == 'Premium') return 1 if(y.type == 'Premium') return -1 if(x.date > y.date) return 1 if(x.date < y.date) return -1 return 0 }).reverse() console.log(obj2)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="script.js"></script> </head> <body> </body> </html>
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.