How to Sort an Array of Objects by a Date in JavaScript

To sort an array of objects by a date value in JavaScript, you can use the “sort()” method and provide a “custom comparison function” that compares the date properties of the objects. The “sort()” method takes a comparison function as its argument, which should return a negative, zero, or positive value depending on the desired order of the two elements being compared.

Example

const objArray = [
  { date: '2023-04-20', value: 'a' },
  { date: '2023-04-22', value: 'c' },
  { date: '2023-04-21', value: 'b' }
];

objArray.sort((a, b) => new Date(a.date) - new Date(b.date));

console.log(objArray);

Output

[
  { date: '2023-04-20', value: 'a' },
  { date: '2023-04-21', value: 'b' },
  { date: '2023-04-22', value: 'c' }
]

In this code, we have an array of objects called objArray, each with a date and value property.

In the next step, we used the “sort()” method with a custom comparison function that takes two objects, a and b, and returns the difference between their date properties as new Date(a.date) – new Date(b.date). This ensures that the objects are sorted in ascending order based on their date properties.

The resulting sorted array has the objects ordered by their dates: ‘2023-04-20’, ‘2023-04-21’, and ‘2023-04-22’.

Leave a Comment