![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 based on min and max date in JavaScript?
Suppose, we have an array of string dates like this −
const arr = [ "2017-01-22 00:21:17.0", "2017-01-27 11:30:23.0", "2017-01-24 15:53:21.0", "2017-01-27 11:34:18.0", "2017-01-26 16:55:48.0", "2017-01-22 11:57:12.0", "2017-01-27 11:35:43.0" ];
We are required to write a JavaScript function that takes in one such array. The function should find the oldest and the newest date from this array.
And then the function should finally return an object containing those two dates.
Example
const arr = [ "2017-01-22 00:21:17.0", "2017-01-27 11:30:23.0", "2017-01-24 15:53:21.0", "2017-01-27 11:34:18.0", "2017-01-26 16:55:48.0", "2017-01-22 11:57:12.0", "2017-01-27 11:35:43.0" ]; const findMinMaxDate = (arr = []) => { const res = arr.reduce((acc, val, ind) => { if (!ind) { return { min: val, max: val}; }; if (val < acc.min) { acc.min = val; }; if (val > acc.max) { acc.max = val; }; return acc; }, undefined); return res; }; console.log(findMinMaxDate(arr));
Output
And the output in the console will be −
{ min: '2017-01-22 00:21:17.0', max: '2017-01-27 11:35:43.0' }
Advertisements