How to sort an array by date value in JavaScript

May 15, 2023#javascript#how-to

JavaScript provides a built-in method called sort() that allows you to sort arrays. The default sort order is ascending, based on converting the elements into strings and comparing their sequences of UTF-16 code units values.

sort()
sort(compareFunction)

However, this default behavior may not work well for sorting dates and time-based data, a custom comparison function is required in this case.

To sort an array of date string in JavaScript, you need to provide a custom compare function that can compare two date strings. For example:

let array = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];

// Sort by date string in ascending order
array.sort(function(a, b) {
  // Convert the date strings to Date objects
  let dateA = new Date(a);
  let dateB = new Date(b);

  // Subtract the dates to get a value that is either negative, positive, or zero
  return dateA - dateB;
});

console.log(array);
// Outputs: [
//   '18/05/2015',
//   '09/06/2015',
//   '22/06/2015',
//   '25/06/2015',
//   '25/07/2015'
// ]

Sorting an array of objects by date property is a special case of sorting an array by object property. Here an example:

let array = [
  {id: 1, date: "Mar 12 2012 10:00:00 AM"},
  {id: 2, date: "Mar 8 2012 08:00:00 AM"}
];

// Sort by date value in ascending order
array.sort(function(a, b) {
  // Convert the date strings to Date objects
  let dateA = new Date(a.date);
  let dateB = new Date(b.date);

  // Subtract the dates to get a value that is either negative, positive, or zero
  return dateA - dateB;
});

console.log(array);
// Outputs: [
//   { id: 2, date: 'Mar 8 2012 08:00:00 AM' },
//   { id: 1, date: 'Mar 12 2012 10:00:00 AM' }
// ]

The compare function takes two elements of the array as parameters, and returns a number that indicates their relative order. If the return value is negative, it means the first element should come before the second element. If the return value is positive, it means the first element should come after the second element. If the return value is zero, it means the elements are equal and their order does not matter.

To compare two date values, we can use the Date object constructor to convert the date strings to Date objects. Then we can subtract them to get a number that represents their difference in milliseconds. The smaller the difference, the closer the dates are.

Note that this method works for any valid date format that can be parsed by the Date object constructor. However, if you have different date formats in your array, you may need to normalize them before sorting. Read how to parse and format a date in JavaScript to handle more complex date operations.

Here is an example of using date-fns library to sort an array by date value in JavaScript:

import { compareDesc } from "date-fns";

let array = [
  {id: 1, date: "Mar 12 2012 10:00:00 AM"},
  {id: 2, date: "Mar 8 2012 08:00:00 AM"}
];

// Sort by date value in descending order
array.sort(function(a, b) {
  // Use compareDesc function from date-fns library
  // It takes two date values and returns a number that indicates their order
  return compareDesc(a.date, b.date);
});

console.log(array);
// Outputs: [
//   { id: 2, date: 'Mar 8 2012 08:00:00 AM' },
//   { id: 1, date: 'Mar 12 2012 10:00:00 AM' }
// ]

The compareDesc function from date-fns library is a convenient way to compare two date values. It returns a negative number if the first date is after the second date, a positive number if the first date is before the second date, and zero if the dates are equal. You can use it as a compare function for the sort() method of the array object.

Note that the compareDesc function can parse various date formats, but it is recommended to use ISO 8601 format for consistency and compatibility. You can also use other functions from date-fns library to manipulate and format dates.

Remember to ensure that the array contains valid date objects for accurate sorting. With this knowledge, you can effectively sort arrays by date values in JavaScript and efficiently manage time-related data in your applications.