Why is it necessary to use compare function while sorting an array as if not used it works in some programs while it doesn’t work in others.
Please share your ideas and possibly if any iterative thinking about how the function works stepwise.
function nonMutatingSort(arr){
return arr.concat([]).sort();
}
The above code works in some test cases while it doesn’t in others.
A test case that it doesn’t work : [1, 30, 4, 21, 100000]
function nonMutatingSort(arr){
return arr.concat([]).sort(function(a,b){
return a-b;
});
}
Careful, your function is called nonMutatingSort but
the array is sorted in place , and no copy is made.
Now, to your question,
If compareFunction is not supplied, all non- undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.
Basically, if you don’t provide a sort function, then JavaScript will sort based on the character codes in the string representation of your array items.