RdnCdn
RdnCdn

Reputation: 183

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?

Upvotes: 6

Views: 893

Answers (4)

mikatuo
mikatuo

Reputation: 800

To summarize (since Elixir v1.10):

Sort by inserted_at (date and time):

... |> Enum.sort_by(& &1.inserted_at, NaiveDateTime)
... |> Enum.sort_by(& &1.inserted_at, {:desc, NaiveDateTime})

Sort by inserted_at (date):

... |> Enum.sort_by(& &1.inserted_at, Date)
... |> Enum.sort_by(& &1.inserted_at, {:desc, Date})

Upvotes: 0

Sinc
Sinc

Reputation: 671

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.

Upvotes: 1

chris
chris

Reputation: 2863

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 )).

Upvotes: 9

Waxhaw
Waxhaw

Reputation: 839

By default a 'map' doesn't provide a 'sorting order'. Not sure what I'm looking at or what language this is in. In Java you would use this type of collection: http://tutorials.jenkov.com/java-collections/sortedmap.html

Upvotes: -3

Related Questions