I can sort the array [1, 3, 2] by calling the .sort() method on it. Optionally, I can pass in a comparison function to do things like sorting the array in reverse. This always works when the array contains Numbers.
However, when the array contains Strings, the .sort() method is unpredictable. It will sort the array if no optional comparison function is provided, but will not sort if a comparison function is provided.
Why does this happen? Is there a workaround?
I have included a code snippet below that illustrates the problem.
let letters;
let numbers;
letters = ["a", "c", "b"];
numbers = [1, 3, 2];
console.log(letters.sort()); // ["a", "b", "c"] DOES SORT
console.log(numbers.sort()); // [1, 2, 3]. DOES SORT
letters = ["a", "c", "b"];
numbers = [1, 3, 2];
console.log(letters.sort((a, b) => a - b)); // ["a", "c", "b"] DOES NOT SORT
console.log(numbers.sort((a, b) => a - b)); // [1, 2, 3] DOES SORT
letters = ["a", "c", "b"];
numbers = [1, 3, 2];
console.log(letters.sort((a, b) => b - a)); // ["a", "c", "b"] DOES NOT SORT
console.log(numbers.sort((a, b) => b - a)); // [3, 2, 1] DOES SORT
numbers.sort()does not work. Try[2, 10].localeCompare.