8
$\begingroup$

SortBy is a wonder and convenient way to sort a list using a list of functions with which ties can be broken.

input = {{x, 0}, {b, 1, 2}, {c, 2}};
SortBy[input, {Length, First}]
(* {{c, 2}, {x, 0}, {b, 1, 2}} *)

However, is there a fast function that will just tell me the position of the element of the input ranked first by SortBy? In the case above, the answer I'm looking for is 3.

I'm looking for a built-in that does this, or a fast function that can get the result for larger (size of ~1000) lists and lots of tie-breaking functions.

$\endgroup$
  • $\begingroup$ If WRI creates such system functions, it should be called MaxBy and MinBy or FirstBy and LastBy. $\endgroup$ – David G. Stork Mar 27 '18 at 17:22
  • $\begingroup$ @JasonB. My v11.3 doesn't know of OrderingBy - where is it implemented? $\endgroup$ – kirma Mar 27 '18 at 17:34
  • $\begingroup$ @DavidG.Stork I don't think those functions (I guess you mean MaximalBy etc.) implement the "tie-breaking" part of the question, which seems either unique to SortBy, or undocumented for other similar functions. Well, unless I'm mistaken. $\endgroup$ – kirma Mar 27 '18 at 17:37
  • $\begingroup$ @kirma: I'm assuming that the yet-to-be-written function would indeed implement tie-breaking rules. $\endgroup$ – David G. Stork Mar 27 '18 at 18:02
  • $\begingroup$ @DavidG.Stork Ah! I missed that small "if" there. $\endgroup$ – kirma Mar 27 '18 at 18:05
9
$\begingroup$

One possibility:

Ordering[Through @* {Length, First} /@ input, 1]

{3}

$\endgroup$
  • $\begingroup$ Very interesting way to represent the tie-breaking concept using the "natural" sorting order of lists! $\endgroup$ – kirma Mar 27 '18 at 17:50
  • $\begingroup$ As a further note: I considered implementing a solution with Fold. Transforming input entries to lists which perform tie-breaking directly on sorting-related functions is million times better an approach. $\endgroup$ – kirma Mar 27 '18 at 18:00
  • 1
    $\begingroup$ Nice! I found this solution too just before I checked on here; good to see agreement. $\endgroup$ – QuantumDot Mar 27 '18 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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