Sort strings using the less / greater comparison operators in the comparator

Today I found a strange implementation for sorting strings:

['Data', 'Chata', 'Clata'].sort(function(a, b) { return a > b});

Using this approach, we take a valid sorted array as a result of - ["Chata", "Clata", "Data"]. But I do not understand why this works ...

I know that the comparator function expects three different outputs - zero, an integer above zero, an integer below zero. But in this case, we can take only two values: true (if greater than b) or false (if less than b) (1 or 0 after the forced type).

Can someone explain to me why this works?

+4
source share
2

, .

EDIT .

1000 (https://jsfiddle.net/alnitak/80cje6gt/), :

var m = 0;
a.sort(function(a, b) { ++m; return a > b} );

var n = 0;
b.sort(function(a, b) { ++n; return a < b ? -1 : a > b ? 1 : 0});
+3

. , c , d ( )

-1

Source: https://habr.com/ru/post/1621733/


All Articles