0

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?

  • Well, the `sort` function is actually doing the sorting. The inner function is a comparator. If you subtract two numbers, and the result is negative, the first number is smaller than the second. Look up how `sort` uses the function given to it. – Carcigenicate Sep 08 '18 at 15:06
  • I suggest getting a piece of paper and pencil and working through a small example by hand. Be sure to read the documentation of `sort()` so that you understand how the return value of the callback function is used. – Code-Apprentice Sep 08 '18 at 15:09
  • Accepted [answer here](https://stackoverflow.com/questions/6567941/how-does-sort-function-work-in-javascript-along-with-compare-function) would be a great starting point – Nachiketha Sep 08 '18 at 15:14
  • Possible duplicate of [How does sort function work in JavaScript, along with compare function](https://stackoverflow.com/questions/6567941/how-does-sort-function-work-in-javascript-along-with-compare-function) – Paul Sep 08 '18 at 15:16
  • i once wrote a long answer on quora .maybe it will help https://www.quora.com/Can-somebody-explain-sort-function-with-a-compare-function-as-a-parameter-in-Javascript/answer/Ashish-Singh-348 – ashish singh Sep 08 '18 at 15:17

1 Answers1

3

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

Paul
  • 35,689
  • 11
  • 93
  • 122