Group maps with same key as one and sort each map

How can I group lists with the same Id into a separate group, for instance

This is my data %{
buyOrder: %{
“data” => [
%{
“amount” => 0.5,
“id” => 1,
“market_currency” => “bitcoin”,
“pair_currency” => “addcoin”,
“pair_name” => “add_btc”,
“price” => 23.4,
“total” => 11.7
},
%{
“amount” => 10.0,
“id” => 2,
“market_currency” => “bezopcoin”,
“pair_currency” => “addcoin”,
“pair_name” => “add_bez”,
“price” => 23.4,
“total” => 234.0
},
%{
“amount” => 0.50,
“id” => 3,
“market_currency” => “bitcoin”,
“pair_currency” => “addcoin”,
“pair_name” => “add_btc”,
“price” => 23.4,
“total” => 11.7
},
%{
“amount” => 15.0,
“id” => 4,
“market_currency” => “bezopcoin”,
“pair_currency” => “addcoin”,
“pair_name” => “add_bez”,
“price” => 23.4,
“total” => 234.0
}
]
}
}

I want to separate this map, in such a way that maps with the same pair_name are grouped together and each new list/map will undergo sorting to be sorted according to their prices, please how can I do that? I want the sorting to sort each data in every list after they have been grouped together by pair_name, in the end, I will have two maps with two maps each, and in the two main maps/groups, the sub-maps will be sorted according to their prices(the higher prices comes first.

1 Like

I do not understand your second requirement, but the first is easily achievable using Enum.group_by/3.

3 Likes

maps are not sorted, if order is important, you have to use lists (or tuples)

2 Likes

To group by pair_name and sort by price (all prices being equal in your example the sorting does not do much though) something like that should work:

to_sort = %{
  buyOrder: %{
    "data" => [
      %{
        "amount" => 0.5,
        "id" => 1,
        "market_currency" => "bitcoin",
        "pair_currency" => "addcoin",
        "pair_name" => "add_btc",
        "price" => 23.4,
        "total" => 11.7
      },
      %{
        "amount" => 10.0,
        "id" => 2,
        "market_currency" => "bezopcoin",
        "pair_currency" => "addcoin",
        "pair_name" => "add_bez",
        "price" => 23.4,
        "total" => 234.0
      },
      %{
        "amount" => 0.50,
        "id" => 3,
        "market_currency" => "bitcoin",
        "pair_currency" => "addcoin",
        "pair_name" => "add_btc",
        "price" => 23.4,
        "total" => 11.7
      },
      %{
        "amount" => 15.0,
        "id" => 4,
        "market_currency" => "bezopcoin",
        "pair_currency" => "addcoin",
        "pair_name" => "add_bez",
        "price" => 23.4,
        "total" => 234.0
      }
    ]
  }
}

to_sort.buyOrder["data"] 
|> Enum.sort_by(&(Map.get(&1, "price")), &<=/2) 
|> Enum.group_by(&(Map.get(&1, "pair_name")))
2 Likes