Order a list from the `snd` tuple in this list:

I have the following list of tuples:

[("a",6),("b",1),("c",2),("d",4),("e",1),("f",1),("g",5),("h",3),("i",1),("j",2)] 

but would like to order tuples in the list with the snd element of the tuple. This way I get a response similar to:

 [("b",1),("e",1),("f",1),("i",1),("c",2),("j",2),("h",3),("d",4),("g",5),("a",6)] 

(i.e. the list is ordered by the second ( snd ) of each tuple.

+4
source share
2 answers
 sortBy (comparing snd) 

where sortBy is in List and comparing is in Data.Ord .

+10
source

Alternatively jleedev answer:

 sortBy (compare `on` snd) 

where sortBy is in Data.List and on is in Data.Function .

IMO, this statement is a little better, because compare is just a standard class method from Ord , and on is a more useful function that comparing . But there is not much.

+5
source

All Articles