0

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?

smartmouse
  • 13,912
  • 34
  • 100
  • 166
  • Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – tevemadar Jul 07 '21 at 14:31

1 Answers1

3

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>
Trillyy
  • 232
  • 3
  • 9
  • Why do you need to use `reverse()` to make it working? Shouldn't you write a "reverse" version of the custom function instead? – smartmouse Jul 07 '21 at 15:10
  • The idea of reverse is simple. Basically what I'm doing is give the most importance on the 'Premium' type. If you would call sort without a custom implementation, you would have everything sorted in ascending mode. That's why I used reverse, to keep that ascending mode. You can remove reverse and swap the indexes (1 instead of -1 and viceversa) to get the same result – Trillyy Jul 07 '21 at 17:52
  • I did try to swap indexes, but I doesn't work. I keep using `reverse()`. Thank you. – smartmouse Jul 08 '21 at 07:45
  • 1
    well, it does work for me [https://jsfiddle.net/Trillyy/9aj0yxuh/](https://jsfiddle.net/Trillyy/9aj0yxuh/) – Trillyy Jul 08 '21 at 12:15
  • Sorry, my bad. Thank you ;) – smartmouse Jul 09 '21 at 10:20