0

Why does this code works?

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
   var points = [40,100,1,5,25,10];
   points.sort(function(a,b){return a-b});
   var x = document.getElementById("demo");
   x.innerHTML=points;
}
</script>
</body>
</html>

It is taken from W3Schools

I am not understanding the points.sort(function(a,b){return a-b}); part.

Pranav 웃
  • 8,469
  • 6
  • 38
  • 48
user5402
  • 291
  • 5
  • 16
  • I don't understand the `points.sort(function(a,b){return a-b});` part. – user5402 Nov 25 '13 at 22:51
  • 1
    Didn't W3Schools explain how Array.sort works? – Yuriy Galanter Nov 25 '13 at 22:53
  • 1
    It uses the built in function sort() to sort the numbers based on the function you pass to sort, in this case `function(a,b){return a-b}`. – DrCord Nov 25 '13 at 22:53
  • http://www.w3fools.com/ for starters This is a duplicate question see http://stackoverflow.com/questions/1494713/how-does-javascripts-sort-work – Ace Nov 25 '13 at 22:57
  • 1
    Also I looooooove W3School's explanation *It can be difficult to understand how this function works, but see the examples at the bottom of this page.*. – Yuriy Galanter Nov 25 '13 at 22:59
  • If you want to understand how sort function working read this [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) or [Sorting Algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm) – Givi Nov 25 '13 at 22:59
  • In order that the function (function(a,b){return a-b}) is called, it should end by () right? Moreover, I don't understand what {return a-b} is for? is it auto-converted to a boolean? – user5402 Nov 25 '13 at 22:59
  • @metacompactness no, `return a-b` returns the result of subtracting `b` from `a`. So for example, the first 2 numbers in the array, `a=40` and `b=100` so `return a-b` would return `-60`. – CrayonViolent Nov 25 '13 at 23:02

5 Answers5

2

What you have is the comparefunction argument syntax of Array.prototype.sort that you can use for customsorting. It performs the sorting based on the value you return from this function and the rules are as follows:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

So you are just returning the difference between 2 numbers a & b which will return exactly what is needed by the sort compareFunction, (i.e -ve --> if a < b, +ve --> if a > b or 0 --> if a == b).

PSL
  • 123,204
  • 21
  • 253
  • 243
1

When you use a callback function with the sort method, it determines how to compare two items in the array.

If the values are equal, the callback function should return 0. If the first parameter should end up before the second, the callback should return a negative value, otherwise a positive value.

Here is a more descriptive implementation with the same result:

points.sort(function(a,b){
  if (a == b) {
    return 0;
  } else if (a < b) {
    return -1;
  } else {
    return 1;
  }
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

The sort function takes a comparator function as its argument. The comparator function works liek this:

  • It compares two values (a and b)
  • If a > b, it returns something positive
  • If a = b, it returns 0
  • If a < b, it returns something negative

a-b fulfills this contract.

For example: if a = 40 and b = 100, then a-b = -60. So a < b.

Samuel
  • 2,106
  • 1
  • 17
  • 27
1

.sort() allows you to pass a function to define how the array is sorted. The goal is to return a positive (>=0) or negative number (<0) in relation to the two currently compared items. The idea is if you take a and subtract from b, if a is greater than b then a positive is returned and therefore a will be ranked higher than b. If a is less than b a negative is returned and b is ranked higher than a.

CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
1

The sort function works by looking at whether the value returned by the comparator function is negative or positive. Basically, if it's positive, it swaps the numbers. If it's negative or zero, it leaves them in that order. It keeps traversing the array until all pairs return a non-positive value.

In this case:

  1. 40-100 = -60 so leave those two alone. Array is [40, 100, 1, 5, 25, 10]
  2. 100-1 = 99 so swap. Array is [40, 1, 100, 5, 25, 10]
  3. 100-5 = 95 so swap. [40, 1, 5, 100, 25, 10]
  4. 100-25= 75 so swap. [40, 1, 5, 25, 100, 10]
  5. 100-10= 90 so swap. [40, 1, 5, 25, 10, 100]
  6. Start over. 40-1 = 39, so swap. [1, 40, 5, 25, 10, 100]

and so on... This is fairly inefficient, so it's likely that under the hood, something more efficient is going on, but for the purposes of predicting your output, this is sufficient.

You could write your sort function like this and get the same result:

function(a, b) {
    if (a > b) return 1;
    else if (a < b) return -1;
    else return 0;
}
Lola
  • 1,878
  • 1
  • 13
  • 11