+ 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.
2 Respuestas
+ 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"]
+ 2
Thanks a lot Schindlabua you nailed it.