Sort an Object Array by Date in JavaScript
Last Updated :
31 May, 2024
To sort an Object Array by Date in JavaScript, we have different approaches. We are going to learn how to sort an Object Array by Date in JavaScript.
Below are the approaches to sort an Object Array by Date in JavaScript:
Using sort
method with Date
objects
This approach uses the built-in sort
method along with Date
objects. The sort
method compares Date
objects directly, sorting the array in ascending order based on the date property.
Example: In this example, we are using the sort method with Date objects.
JavaScript
const data = [
{ name: 'Event 1', date: new Date('2023-01-15') },
{ name: 'Event 2', date: new Date('2022-12-20') },
{ name: 'Event 3', date: new Date('2023-03-05') }
];
// Sorting the array based on the 'date' property
data.sort((a, b) => a.date - b.date);
console.log(data);
Output[
{ name: 'Event 2', date: 2022-12-20T00:00:00.000Z },
{ name: 'Event 1', date: 2023-01-15T00:00:00.000Z },
{ name: 'Event 3', date: 2023-03-05T00:00:00.000Z }
]
Using sort()
method with getTime()
method
Similar to the first approach, this method uses the sort
method but employs the getTime
method on Date
objects to obtain their numeric representations. Sorting is done based on these numeric values.
Example: In this example, we are using sort
method with getTime
method.
JavaScript
const data = [
{ name: 'Event 1', date: new Date('2023-01-15') },
{ name: 'Event 2', date: new Date('2022-12-20') },
{ name: 'Event 3', date: new Date('2023-03-05') }
];
// Sorting the array based on the 'date' property
data.sort((a, b) => a.date.getTime() - b.date.getTime());
console.log(data);
Output[
{ name: 'Event 2', date: 2022-12-20T00:00:00.000Z },
{ name: 'Event 1', date: 2023-01-15T00:00:00.000Z },
{ name: 'Event 3', date: 2023-03-05T00:00:00.000Z }
]
Using a custom sorting function
In this approach, a custom sorting function (sortByDate
) is defined, which compares the date
properties of the objects. This function is then used as an argument for the sort
method to achieve the desired sorting.
Example: In this example, we are Using a custom sorting function
JavaScript
const data = [
{ name: 'Event 1', date: new Date('2023-01-15') },
{ name: 'Event 2', date: new Date('2022-12-20') },
{ name: 'Event 3', date: new Date('2023-03-05') }
];
// Custom sorting function
const sortByDate = (a, b) => {
return a.date - b.date;
};
// Sorting the array based on the 'date' property using the custom function
data.sort(sortByDate);
console.log(data);
Output[
{ name: 'Event 2', date: 2022-12-20T00:00:00.000Z },
{ name: 'Event 1', date: 2023-01-15T00:00:00.000Z },
{ name: 'Event 3', date: 2023-03-05T00:00:00.000Z }
]
Using Lodash _.orderBy() Method
Lodash _.orderBy() method is similar to the _.sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort.
Syntax:
_.orderBy(Collection, [ iteratees ], [ orders ]);
Example: In this example, we are sorting the array’s patron in ascending order and age in descending order.
JavaScript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = [
{ 'patron': 'jonny', 'age': 48 },
{ 'patron': 'john', 'age': 34 },
{ 'patron': 'john', 'age': 40 },
{ 'patron': 'jonny', 'age': 36 }
];
// Use of _.orderBy() method
// Sort by `patron` in ascending order
// and by `age` in descending order
let sorted_array =
_.orderBy(users, ['patron', 'age'],
['asc', 'desc']);
// Printing the output
console.log(sorted_array);
Output:
[
{ 'patron': 'john', 'age': 40 },
{ 'patron': 'john', 'age': 34 },
{ 'patron': 'jonny', 'age': 48 },
{ 'patron': 'jonny', 'age': 36 }
]
To sort an object array by date using `Intl.DateTimeFormat` and `Array.prototype.sort()`, convert the date strings to formatted dates, then use the `sort` method with a custom compare function that compares the formatted dates.
Example: In this example we defines an array of objects with dates, sorts the array by the date property using Intl.DateTimeFormat.
JavaScript
const array = [
{ id: 1, date: '2022-01-15' },
{ id: 2, date: '2023-03-20' },
{ id: 3, date: '2021-09-10' }
];
array.sort((a, b) => new Intl.DateTimeFormat('en-US').format(new Date(a.date)) -
new Intl.DateTimeFormat('en-US').format(new Date(b.date)));
console.log(array);
Output[
{ id: 1, date: '2022-01-15' },
{ id: 2, date: '2023-03-20' },
{ id: 3, date: '2021-09-10' }
]
Similar Reads
JavaScript - Sort JS Arrays of Objects by Date Key
The following approaches can be used to sort the array of objects by Date as KeyUsing Array.sort() with Comparison FunctionUse the comparison function to sort the array of objects (complex array).JavaScriptconst arr = [ { name: 'Geeks', date: '2022-03-15' }, { name: 'Abc', date: '2022-03-12' }, { na
3 min read
Sort an Array in JavaScript
This article will show you how to sort a JS array.1. Using array.sort() Method To sort an array in JavaScript, we can use array.sort() method. This method sorts the elements alphabetically in ascending order.JavaScriptlet arr = ["JS", "HTML", "CSS"]; arr.sort() console.log(arr);Output[ 'CSS', 'HTML'
3 min read
Sort An Array Of Arrays In JavaScript
The following approaches can be used to sort array of arrays in JavaScript.1. Using array.sort() Method- Mostly UsedJS array.sort() is used to sort and update the original array in ascending order.JavaScriptlet arr = [[3, 2], [1, 4], [2, 5], [2, 0]]; arr.sort(); console.log(arr);Output[ [ 1, 4 ], [
2 min read
How to sort an array of object by two fields in JavaScript ?
We have given an array of objects and the task is to sort the array of elements by 2 fields of the object. There are two methods to solve this problem which are discussed below: Approach 1:First compare the first property, if both are unequal then sort accordingly.If they are equal then do the same
3 min read
How to Sort an Array of Objects Based on a Key in JavaScript ?
In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order. Table of Content Using sort() methodUsing Custom Sorting FunctionUsing Lodash _.orderBy() MethodUsin
3 min read
How to Access Array of Objects in JavaScript ?
Accessing an array of objects in JavaScript is a common task that involves retrieving and manipulating data stored within each object. This is essential when working with structured data, allowing developers to easily extract, update, or process information from multiple objects within an array.How
4 min read
JavaScript- Convert an Object to JS Array
Objects in JavaScript are the most important data type and form the building blocks for modern JavaScript. These objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). Methods to convert the Objects to JavaScript Array:1. Using Obje
3 min read
How to compare Arrays of Objects in JavaScript?
In JavaScript, comparing arrays of objects can be more complex than comparing primitive data types. We will discuss different ways to compare arrays of objects effectively, with detailed code examples and explanations.Syntax: Before going to detail the comparison techniques, let's first understand h
5 min read
How to Sort a Multidimensional Array in JavaScript by Date ?
Sorting a Multidimensional Array by date consists of ordering the inner arrays based on the date values. This needs to be done by converting the date representation into the proper comparable formats and then applying the sorting function to sort the array in ascending or descending order. Below are
2 min read
Sort an array of objects using Boolean property in JavaScript
Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. There are two approaches that are discussed below: Table of Content Using Array.sort() Method and === OperatorUsing Array.sort() and reverse() MethodsUsing a
2 min read