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?