Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of timestamps using lodash in desc order

I want to sort the following array of timestamps using lodash so the latest time stamp is first [3].

Code:

let timestamps = ["2017-01-15T19:18:13.000Z", "2016-11-24T17:33:56.000Z", "2017-04-24T00:41:18.000Z", "2017-03-06T01:45:29.000Z", "2017-03-05T03:30:40.000Z"]

const sorted = _.sortBy(timestamps);

This does not work as i expect, i believe its sorting them but in asc order.

like image 717
Kay Avatar asked Apr 05 '18 13:04

Kay


People also ask

How do you sort an array of objects in Lodash?

The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements.

How do you sort an object array by date property?

To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.

Does Lodash groupBy preserve order?

Does Lodash groupBy preserve order? groupBy , but it does preserve the order of array-like collections, and that's probably unlikely to change. So the sub-items within groups would retain their original ordering, but the grouped key ordering may change, because they are object properties.


2 Answers

orderBy allows you to specify the sort orders while sortBy does not.

const sorted = orderBy(timestamps, ['desc']);
like image 66
Stephanie Avatar answered Sep 28 '22 04:09

Stephanie


How to sort an array of timestamps using lodash

This code is already sorting timestamps correctly using lodash:

const sorted = _.sortBy(timestamps);

just in ascending order, simply reverse the result using:

const sorted = _.sortBy(timestamps).reverse();
like image 30
Aramil Rey Avatar answered Sep 28 '22 05:09

Aramil Rey