- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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' } ]
- Related Articles
- Sort nested array containing objects ascending and descending according to date in JavaScript
- Sort array of objects by string property value - JavaScript
- Sort the second array according to the elements of the first array in JavaScript
- Sort array of objects by string property value in JavaScript
- Sort an array according to another array in JavaScript
- How to sort array according to age in JavaScript?
- How to sort date array in JavaScript
- Sort Array of objects by two properties in JavaScript
- How to sort an array of objects based on the length of a nested array in JavaScript
- Sorting objects according to days name JavaScript
- Sort an array according to the order defined by another array in C++
- Add property to common items in array and array of objects - JavaScript?
- JavaScript Bubble sort for objects in an array
- Sort array based on presence of fields in objects JavaScript
- Sort an array of objects by multiple properties in JavaScript

Advertisements