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?
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 ))
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With