While attempting to sort a JavaScript array, I came across an unexpected behavior.
var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k'];
arr.sort(function (a, b) {
console.log(a, b);
if (a.length < b.length) return 1;
else if (a.length > b.length) return -1;
else return 0;
});
Everything works perfectly in this scenario and returns the same array.
The console output looks like this:
https://i.sstatic.net/b40hn.png
However, when I try sorting with the following input,
var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k', 'l'];
The result is different:
https://i.sstatic.net/w6C2A.png
I am puzzled by this inconsistency and unable to determine the cause of it.
For your information, I implemented this custom sorting logic to arrange elements based on their length.