Usage of compare function while sorting

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;
});
}

The above code works in all the given test cases.

Careful, your function is called nonMutatingSort but

the array is sorted in place , and no copy is made.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

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.

As an example of what Jeremy is talking about:

const arr = [1, 22, 14, 3];

console.log(arr.sort());
// [1, 14, 22, 3]

console.log(arr.sort((a, b) => a - b));
// [1, 3, 14, 22]
1 Like