I think there is an issue with the fact that you are using the default behaviour of sort(), check what happens if you try to sort like that an array like [1, 2, 3, 11, 21, 31] (the result of the method here is [1, 11, 2, 21, 3, 31] - this is because as default behaviour the sort method convert everything to string and order them by Unicode point value)
Also, you don’t need the loop, think of how indexOf() works