How does Comparison function arguments in sorting Arrays in Javascript work. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How does Comparison function arguments in sorting Arrays in Javascript work.

Please I still do not understand the function passed as arguments in the Array sort() method. Major questions are: (1) What is the use of the minus (-) operator in the returned arguments?. (2) Are the parameters picking two options from the Arrays and subtracting them?     var numbers = [ 1, 5, 8, 4, 7, 10, 2, 6 ];      numbers.sort(function(first, second) {     return first - second;     }); Basically It outputs:     [1, 2, 4, 5, 6, 7, 8, 10] Why is that so?  Thanks a lot.

29th Aug 2017, 7:34 PM
Elvis Ngboki
Elvis Ngboki - avatar
2 Answers
+ 3
Sort does some smart stuff to sort an array in as little time as possible. You can imagine it as the sort function going through the array a couple of times, and always comparing two elements of the array, putting the smaller of those two elements before the large one. And if the sort function does it often enough, eventually the array comes out sorted. What it wants to know from you is - which of the two elements it just picked out is larger? - If you return a number smaller than 0, the second one is larger. - If you return a number bigger than 0, the first one is larger. - If you return 0, they are equal. And if you think about it, "first - second" will do just that! It's very flexible and you can sort lots more than numbers with this system. Check this: var animals = ["elephant", "dog", "mike tyson", "giraffe"]; var sorted_by_length = animals.sort(function(a, b){ return a.length - b.length; }); // ["dog", "giraffe", "elephant", "mike tyson"]
29th Aug 2017, 8:14 PM
Schindlabua
Schindlabua - avatar
+ 2
Thanks a lot Schindlabua you nailed it.
29th Aug 2017, 8:27 PM
Elvis Ngboki
Elvis Ngboki - avatar