Sort the item inside keyword list

Hi, I have a list as follow:

[%{“name” => “zzzaazzzzaa”, “phone” => “+919538700004”},
%{“name” => “aaaa”, “phone” => “+919538700003”},
%{“name” => “AAAA”, “phone” => “+919538700002”},
%{“name” => “Chandan”, “phone” => “+919538700001”},
%{“name” => “chandan”, “phone” => “+919538700000”},
%{“name” => “Chethan”, “phone” => “+919538711111”},
%{“name” => “Akash”, “phone” => “+919538722222”},
%{“name” => “bharath”, “phone” => “+919538733333”},
%{“name” => “abhi”, “phone” => “+919538744444”},
%{ “name” => “Test M”, “phone” => “+919538755555”}]

Now i need to sort this according to name by ascending order. How can I achieve that??

Thank you.

With Enum.sort/2:

[...] |> Enum.sort(& &1["name"] <= &2["name"])

2 Likes

Thank you Mam :slight_smile: But is this a case sensitive?? First it is sorting the names which start with the capital letters and then followed by small letters.

1 Like

I’d rather suggest Enum.sort_by(& &1["name"]), so you don’t have to care about how the sorting works and if you need case insensitive sorting just lowercase the comparable value: Enum.sort_by(& String.downcase(&1["name"]))

4 Likes

Woww :grinning::grinning: thank you soo much :+1:

1 Like

I can highly recommend that you read through the documentation for Enum (as well as String, List, etc.) whenever you need to do something that these modules seem to cover.

And I mean the whole thing! even if you just skim through all the functions to get a quick idea of what they do.

I’m by no means a great programmer, but doing this has helped me a ton to find or remember a particular function that does exactly what I need.

For example, after reading your question I immediately went for Enum.sort. Which is fine, but now I’ve been reminded that Enum.sort_by would probably been a better solution in this particular case. I’ve definitely used it before, but I just forgot.

1 Like