Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort array according to the date property of the objects JavaScript
We are required to write a JavaScript function that takes in an array of objects of dates like this −
const arr = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"},
{date: "2017-01-18 17:30:21"},
{date: "2017-01-18 17:24:00"}
];
We are required to write a JavaScript function that takes in one such array. The function should then sort the array according to the date property of the objects.
Example
const arr = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"},
{date: "2017-01-18 17:30:21"},
{date: "2017-01-18 17:24:00"}
];
const sortByTime = (arr = []) => {
arr.sort((a, b) => {
const dateA = new Date( a.date );
const dateB = new Date( b.date );
return dateA < dateB ? -1 :
( dateA > dateB ? 1 : 0);
});
};
sortByTime(arr);
console.log(arr);
Output
And the output in the console will be −
[
{ date: '2016-04-26 20:01:00' },
{ date: '2016-06-08 18:10:00' },
{ date: '2017-01-18 17:24:00' },
{ date: '2017-01-18 17:30:21' },
{ date: '2017-02-06 14:38:00' }
]Advertisements