Brendan Eich brendan at
Sun Apr 1 15:53:53 PDT 2012

Peter van der Zee wrote:
> No idea whether this has been discussed before, but I find myself
> continuously doing this when sorting arrays with objects:
> arr.sort(function(a,b){ if (a.prop<  b.prop) return-1;  if (a.prop>
> b.prop) return 1; return 0; });

With arrows it is better:

arr.sort((a, b) =>  { if (a.prop<  b.prop) return-1;  if (a.prop>  b.prop) return 1; return 0; });

With ?: it's even better:

arr.sort((a, b) =>  (a.prop<  b.prop) ?-1 :  (a.prop>  b.prop) ? 1 : 0);

and if you weed out NaN to avoid the comparison function returning NaN, while taking advantage of the fact that the return value's sign is all that matters, not exact {-1, 0, 1} membership, then it's not much worse:

arr.sort((a, b) =>  { let t = a.prop - b.prop; return (t !== t) ? 0 : t; });

I'm assuming you don't need to sort -0<  0 (which evaluates to false in JS).

Another observation: this last version is the only one that avoids multiple implicit conversions via toString or valueOf of an object operand, if one or both of a and b is an object and the first condition (a.prop<  b.prop) evaluates to false. This means the only portable form is the last version.

Yeah, it's a pain to write every time and people will mess up the NaN corner case. A standard built-in would be good. But why use a string parameter key instead of just a built-in function?


More information about the es-discuss mailing list