An algorithm that I am implementing requires to sort an array in reverse lexical ordering. However, after discovering some incorrect results I found that this line is causing some trouble:
someArray.slice().sort((a, b) => b - a);
Further investigations show that the above is not equivalent to the following statement:
someArray.slice().sort().reverse();
For example,
var someArray = ["11", "2", "1"];
someArray.slice().sort().reverse(); // ["2", "11", "1"]
someArray.slice().sort((a, b) => b - a); // ["11", "2", "1"]
The problem with .sort((a, b) => b - a)
is that b - a
is casting the values to numbers, as thus not sorting by the correct lexical ordering.
Currently my solution is to do b.localeCompare(a)
, but that assumes both a
and b
contain only "English" characters in order for the two statements to be equivalent.
An obvious but ugly solution is this:
someArray.slice().sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
but this seems very long and unnecessary. Is there a better way to sort an array in reverse lexical order?