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?

5
  • 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. Commented Sep 8, 2018 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. Commented Sep 8, 2018 at 15:09
  • Accepted answer here would be a great starting point Commented Sep 8, 2018 at 15:14
  • Possible duplicate of How does sort function work in JavaScript, along with compare function Commented Sep 8, 2018 at 15:16
  • i once wrote a long answer on quora .maybe it will help quora.com/… Commented Sep 8, 2018 at 15:17

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

You’re correct. This is how the sort method in many programming languages works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.