While trying to sort a JavaScript array, I came across strange 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;
});
Run codeHide resultWorks well in this case, returning me the same array.
The console is as follows:

But when I try to do it below
var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k', 'l'];
Gives me this

I canโt understand why this is happening.
PS. I am writing this custom sort by checking the length of the elements because I need an array that has its elements sorted by length.
source
share