1

I have a immutable map and I am trying to sort based on the two properties. For example, The format of the data I have:

const items = [
               {id:1,created:2020:12:12T10:12:56,start:2020:12:10},
               {id:1,created:2020:12:12T10:12:58,start:2020:12:09},
               {id:1,created:2020:12:12T10:12:57,start:2020:12:08},
               {id:1,created:2020:12:12T10:12:53,start:2020:12:09},
              ]

I want to sort that items based on the two properties "created" and "start". I can probably do that:

const sorted = items.sort((a, b) => new Date(b.get('created')) - new Date(a.get('created')));

Is there any way I can sort together with the start property as well like:

 const sorted = items.sort((a, b) => new Date(b.get('created')) - new Date(a.get('created')) && new Date(b.get('start')) - new Date(a.get('start')) );

Is that correct or does anybody know a good approach to accomplish that. Thanks in Advance

ninja
  • 167
  • 2
  • 12
  • You want to sort first by "created" then by "start"? – djcaesar9114 Jun 03 '20 at 11:29
  • probably reverse way,first start and then by created – ninja Jun 03 '20 at 11:32
  • You need the `||` operator instead of `&&`. See [here](https://stackoverflow.com/questions/13211709/javascript-sort-array-by-multiple-number-fields) – trincot Jun 03 '20 at 11:34
  • can you explain it a bit @trincot why do I need to use || operator instead of &&? – ninja Jun 03 '20 at 11:36
  • if the first subtraction is non zero the other becomes irrelevant, and so you don't need `&&` as that needs to check whether the other is non zero as well. Did you read the accepted answer of the Q&A I linked to? – trincot Jun 03 '20 at 11:40
  • I read that but mine was immutable format and that's why wanted to ask this question again, if it has some other ways to do it – ninja Jun 03 '20 at 11:45
  • Unfortunately the question got closed before i could post an answer. [Here is a simple helper function that sorts by multiple fields](https://gist.github.com/C5H8NNaO4/15f9b776ce7e4540eacb64b77e3b711d) – Moritz Roessler Jun 03 '20 at 11:45

1 Answers1

0

I would do something like this (I didn't check but the principle is to chain 2 sort ):

const sorted = items.sort((a, b) => new Date(b.get('created')) - new Date(a.get('created'))).sort((a, b) => new Date(b.get('start')) - new Date(a.get('start')))
djcaesar9114
  • 1,880
  • 1
  • 21
  • 41