0

I have an array of objects with a date format that looks this way:

"offline_available": "5/1/2021"

As I understand it is the date formatted by the toLocaleDateString() method.

How can I sort all objects by next available date?

jakhando
  • 113
  • 1
  • 9
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Henrik Erstad Nov 16 '20 at 08:04
  • @henrik-erstad I don't think so. Here I'm working with dates, I believe it should have another approach. The main thing is how to compare dates in this format as I pointed out. – jakhando Nov 16 '20 at 08:09
  • The output of *toLocaleString* is implementation dependent and is affected by browser and system settings. My system produces something like "17/11/2020, 13:09:02". There is no requirement for the output to be parsed by the built-in parser, so `new Date(new Date().toLocaleString())` may produce a correct, incorrect or invalid Date. – RobG Nov 17 '20 at 03:08

2 Answers2

0

Start with this - assuming the date is mm/dd/yyyy

const arr = [
{"offline_available": "5/1/2021"},
{"offline_available": "12/13/2020"},
{"offline_available": "5/3/2020"},
{"offline_available": "5/3/2021"}
]
const sorted = arr.slice(0).sort((a,b) => new Date(a.offline_available) - new Date(b.offline_available))
console.log(sorted)

What is "sort by next available date"?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You need to translate your date string into a date object in the comparison function.

 yourArray.sort( (a,b) => new Date(a.offline_available) - new Date(b.offline_available))
PA.
  • 28,486
  • 9
  • 71
  • 95
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Nov 17 '20 at 03:06