Reputation: 480
I was working on some coding challenges for practice and came across one that stumped me. Reading an article about it, I came across the answer, which I cannot understand. The challenge was to create a function that sorts an array of integers in ascending order and returns it. The function is as follows:
function sortAscending(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
What I can't understand is how sorting using the compare function return a - b
actually works. If I have an array of random integers and I take a calculator and apply that arithmetic operation to each, it does not result in an array that is sorted in ascending order, it results in a completely different array. So that tells me I must be completely misunderstanding how this work. Anyone care to explain this to someone with basically no computer science knowledge?
Upvotes: 0
Views: 58
Reputation: 36319
Your compare function (a,b) => a-b
is telling the sort
function how to sort. In other words, it tells sort
how to compare two values at a time. Internally, sort
applies your compare function repeatedly until it comes up with the sorted results.
if the return value is less than zero, a should be sorted to an index less than b (so a is placed in the array before b)
If the return value is greater than zero, a should be sorted to an index greater than b.
If the return value IS zero, then the order should remain unchanged.
Any undefined
value (in either a or b) gets sorted to the end of the array w/o actually calling the compare function.
This is well documented on MDN
Upvotes: 3