Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to orderBy an array of dates(desc) while maintaining (asc) SAME day times

I need to order an array of dates with their times in descending order but the times remain in ascending order with lodash.

const supplierDates = ["2022-02-14 07:00", "2022-02-14 08:00", "2022-02-14 10:00", "2022-02-17 19:00", "2022-02-18 18:00"
results = _.orderBy(supplierDates, suppDate => suppDate, ['desc']);

This sorts the array in descending order but I am interested in maintaining an ascending order for SAME day times (in this case, 14th Feb)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This happens because you are sorting strings, while you want to sort dates.

Use substring to extract ONLY the date from your strings, and then use Date.parse to parse to dates so you can sort them:

const supplierDates = ["2022-02-14 07:00", "2022-02-14 08:00", "2022-02-14 10:00", "2022-02-17 19:00", "2022-02-18 18:00"];
const results = _.orderBy(supplierDates, suppDate => Date.parse(suppDate.substring(0, 10)), ['desc']);

console.log(results);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading