Skip to content
Advertisement

JS sort array by two columns of Dates

I am trying to sort an multidimensional array by dates in two columns. Each element of the array looks like that [Thu Feb 25 10:00:00 GMT-05:00 2021, Tue Mar 09 10:00:00 GMT-05:00 2021, 1326M98301, 1326M98301, product 3, 1.0, 2.188120526039E12]

I want to sort it first by the second column and then by the first. Lets say that first column is as order day and the second is delivery day so I just want to know which should be shipped first. I guess that’s the simplest way I can explain it…

So the output should look like this:

JavaScript

Maybe the screenshot will be easier to look at: enter image description here

So, I managed to write a code that do the job but only for one month and only one day. This is the point where I realized that now I would have to write different variables for every day of the month which is not good I guess… and of course not every month has exactly 30 days, so there would be an error some day… I have now idea how could I solve this problem.

My approach was:

  1. From whole array take only one month – column 2 (original data has more than one month)
  2. Create an array for each day of that month
  3. Sort array of a day (by the first column)
  4. Join all sorted arrays

If anyone would like to help me with this problem I would appreciate it.

My code so far:

JavaScript

Advertisement

Answer

We can create a sortDates function to sort the dates, using Date.parse to get the unix time for each date, then compare to first by column 2, then by column 1.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement