Your arr.sort() is the problem. You need read the information in the sort function (available at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). You need to add a compare function. Currently, without the compare function, the array is sorted according to each character’s Unicode code point value, according to the string conversion of each element. If you add a console.log(arr) on the line following the sort I mentioned above, you will see what the array looks like after sorting but before going into the for loop logic.
Also, instead of sorting the array multiple times in the for loop which is not efficient, just move the sort to right before the for loop, so it only sorts one time.