How to usesort() Method in Javascript
First, we will create an array of an object containing the date key, then apply the sort() method to sort an array of objects using the date key.
Syntax:
array.sort((a, b) => a.date - b.date);
Example: In this example, we sort the arr array of objects by the date property in ascending order using the sort() method and subtraction.
const arr = [
{ name: 'Geeks', date: new Date('2022-03-15') },
{ name: 'Abc', date: new Date('2022-03-12') },
{ name: 'GFG', date: new Date('2022-03-20') },
{ name: 'G4G', date: new Date('2021-03-20') }
];
arr.sort((a, b) => a.date - b.date);
console.log(arr);
Output
[ { name: 'G4G', date: 2021-03-20T00:00:00.000Z }, { name: 'Abc', date: 2022-03-12T00:00:00.000Z }, { name: 'Geeks', date: 2022-03-15T00:00:00.000Z }, { name: 'GFG', date: 2022-03-20T00:00:00.000Z } ]
Sort array of objects by single key with date value in JavaScript
In this article, we will see how to sort an array of objects by a single key with a date value in JavaScript. For sorting the array of objects we can use the sort() method which basically calls the callback function as an argument.
To sort the array of objects by a single key, we will use the following approaches: