Search code examples
sortingelixirphoenix-framework

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?


Solution

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