# Sort pairs — first elements by order of appearance, second elements numerically

I have a long table in this form:

A = {{a, 1}, {c, 2}, {b, 5}, {c, 1}, {a, 14}, {b, 7}, {b, 10}, {c, 6}, {a, 4}}


and I want to order it by the second column, but first all with an "a" in the first element should be ordered. And then by order of appearance. It should look like this:

{{a, 1},{a, 4},{a, 14},{c, 1},{c, 2},{c, 6},{b, 5},{b, 7},{b, 10}}

SortBy[A, #[[2]] &] would sort the second column, ignoring the first.

Any ideas? Maybe a for-loop?

• So, you don't want SortBy[A, {#[[1]] &, #[[2]] &}]? Mar 31, 2017 at 12:50
• Why don't you use just Sort[A] ? Mar 31, 2017 at 12:52
• If you want it as in the OP, just try Sort /@ GatherBy[A, First]. Mar 31, 2017 at 12:59
• Thank you! Sort /@ GatherBy[A, First] was what I wanted. The other two answers would also sort the first element alphabetically. I wanted it by order of appearance. Mar 31, 2017 at 13:34

A = {{a, 1}, {c, 2}, {b, 5}, {c, 1}, {a, 14}, {b, 7}, {b, 10}, {c, 6}, {a, 4}};

{{{a, 1}, {a, 4}, {a, 14}}, {{c, 1}, {c, 2}, {c, 6}}, {{b, 5}, {b, 7}, {b, 10}}}
• To get the specified output you need to include a Flatten: Flatten[Sort /@ GatherBy[A, First], 1] Mar 31, 2017 at 16:45
• Or Catenate instead of Flatten. Mar 31, 2017 at 16:55