7
$\begingroup$

After long searching, I noticed that the SortBy[list,f] function has an annoying side effect: If the function f yields the same value for consecutive elements of the list, those are still sorted using the canonical ordering of the elements. This is very annoying - I want to sort only on the first element of a list but leave the order of list elements unchanged if the first element is not changing. How can this be achieved?

e.g.:

    y1 = {{1., 2.}, {1., 1.}, {3., 2.}}
    SortBy[y1, #[[1]] &]

Gives:

    {{1.,1.},{1.,2.},{3.,2.}}

But I would like to obtain:

    {{1.,2.},{1.,1.},{3.,2.}}


    
$\endgroup$
2
  • $\begingroup$ I can verify this, MMA 12.3 Windows $\endgroup$ Jun 4, 2021 at 15:46
  • 2
    $\begingroup$ Or, even better, stackoverflow.com/q/3304632, which was referenced in the question cited by @LeonidShifrin $\endgroup$
    – bbgodfrey
    Jun 4, 2021 at 16:48

1 Answer 1

9
$\begingroup$
SortBy[y1, {#[[1]] &}]
{{1., 2.}, {1., 1.}, {3., 2.}}
$\endgroup$
2
  • $\begingroup$ Nice - thanks! Too bad that this is not better described in Help. $\endgroup$
    – hippo3773
    Jun 5, 2021 at 15:59
  • $\begingroup$ Or you can use SortBy[y1, {#[[1]] &, Nothing}] or SortBy[y1, {#[[1]] &, #[[1]] &}] if you need to have multiple explicit functions in the second argument. $\endgroup$ Nov 24, 2022 at 13:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.