Skip to content
the poor coder

sort array iso string date

Poor Man
Published
Reading time
1 min read

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:

Text

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:

Text

["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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC