sort array iso string date

Sorting an Array of ISO String Dates in HTML

Sorting an array of ISO string dates can be a challenging task. One of the most effective ways to accomplish this is to convert the strings into date objects and then sort them using JavaScript's built-in sort() method.

Here's an example of how you can sort an array of ISO string dates:


var dates = ['2022-01-01T00:00:00.000Z', '2021-12-31T00:00:00.000Z', '2021-12-30T00:00:00.000Z'];
dates.sort(function(a, b) {
  return new Date(a) - new Date(b);
});
console.log(dates);

This code will output the following:


["2021-12-30T00:00:00.000Z", "2021-12-31T00:00:00.000Z", "2022-01-01T00:00:00.000Z"]

Explanation:

  1. An array of ISO string dates is created and assigned to the variable 'dates'.
  2. The sort() method is called on the 'dates' array, with a callback function that converts each element into a date object.
  3. The callback function returns the difference between the two date objects, which determines the order of the elements in the sorted array.
  4. The sorted 'dates' array is logged to the console.

Another way to sort an array of ISO string dates is by using the localeCompare() method:


var dates = ['2022-01-01T00:00:00.000Z', '2021-12-31T00:00:00.000Z', '2021-12-30T00:00:00.000Z'];
dates.sort(function(a, b) {
  return a.localeCompare(b);
});
console.log(dates);

This code will output the same result as the previous example.

Explanation:

  1. An array of ISO string dates is created and assigned to the variable 'dates'.
  2. The sort() method is called on the 'dates' array, with a callback function that uses the localeCompare() method to compare the elements as strings.
  3. The sorted 'dates' array is logged to the console.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe