Search code examples
sortingelixirphoenix-framework

Sort List of Maps based on a value within the Map


I have this list:

  [%Statcasters.PredictionScore{__meta__: #Ecto.Schema.Metadata<:loaded, "prediction_scores">,
  id: 1, inserted_at: ~N[2018-01-15 20:24:33.838946],
  league: #Ecto.Association.NotLoaded<association :league is not loaded>,
  league_id: 1, points: 4,
  prediction: #Ecto.Association.NotLoaded<association :prediction is not loaded>,
  prediction_id: 1,
  question: #Ecto.Association.NotLoaded<association :question is not loaded>,
  question_id: 1, updated_at: ~N[2018-01-15 20:24:33.838952]},
 %Statcasters.PredictionScore{__meta__: #Ecto.Schema.Metadata<:loaded, "prediction_scores">,
  id: 2, inserted_at: ~N[2018-01-15 20:24:33.842205],
  league: #Ecto.Association.NotLoaded<association :league is not loaded>,
  league_id: 1, points: 3,
  prediction: #Ecto.Association.NotLoaded<association :prediction is not loaded>,
  prediction_id: 2,
  question: #Ecto.Association.NotLoaded<association :question is not loaded>,
  question_id: 1, updated_at: ~N[2018-01-15 20:24:33.842210]}]

As you can see each map has a points key. I want to sort the maps within the list and return the lowest point integer map to be the first element of the list.

Current attempt:

Enum.map(points, fn(p) -> p.points end) |> Enum.sort

This doesn't work because it returns only the points sorted. I need the entire map.


Solution

  • I believe Enum.sort_by/3 is what you want:

    Enum.sort_by(points, fn(p) -> p.points end)
    

    EDIT: to sort by multiple columns, put them in a tuple/list:

    Enum.sort_by(points, fn(p) -> {p.points, p.coordinate} end)