Saturday, September 7, 2019

javascript - Sort strings by using "less/greater than" comparison operators in comparator

Today I found a strange for me implementation of strings sorting:




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


Using this approach we take a valid sorted array as the output - ["Chata", "Clata", "Data"].
But I don't clearly understand why it works...



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



Can anybody explain me why it works?

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...