Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of time stamps not sorting properly

Sorted list of time stamps

I have a list of maps each with a key stating the "inserted_at" time in which the items were inserted in my database. I want to sort this list in descending order to show the most recent items first. I thought I had it but when looking closer for some reason the 2nd and 3rd elements should be swapped as well as the 5th and 6 elements.

Any idea?

like image 797
RdnCdn Avatar asked Feb 06 '18 02:02

RdnCdn


2 Answers

That's because you are comparing NaiveDateTime in Elixir.

You should use compare method instead of ==, >, <.

e.g, Enum.sort(z, &(NaiveDateTime.compare(&1, &2)==:gt )).

like image 85
chris Avatar answered Nov 07 '22 18:11

chris


According to the release notes for Elixir v10 below this issue should be fixed natively.

Elixir v1.10 streamlines the sorting functions by introducing both :asc and :desc shortcuts:

iex> Enum.sort(["banana", "apple", "pineapple"], :asc)
["apple", "banana", "pineapple"]
iex> Enum.sort(["banana", "apple", "pineapple"], :desc)
["pineapple", "banana", "apple"]

As well as adding the possibility to pass a module to perform semantic comparisons. For example, to sort dates, one now only needs to pass the Date module or even {:desc, Date} for descending semantical sort:

iex> Enum.sort([~D[2019-12-31], ~D[2020-01-01]], Date)
[~D[2019-12-31], ~D[2020-01-01]]
iex> Enum.sort([~D[2019-12-31], ~D[2020-01-01]], {:desc, Date})
[~D[2020-01-01], ~D[2019-12-31]]

These API improvements make the code more concise and readable and they have also been added to Enum.sort_by, Enum.min_by, Enum.max_by, and friends.

like image 23
Sinc Avatar answered Nov 07 '22 19:11

Sinc