As already asked: how does sort function work in JavaScript, along with the compare function?
If I have an array, and I do array.sort(compare) now it was written in the book that if the compare function returns a-b (two indices of the array) then it works based on the fact that whether the result is greater than 0, less than 0 or equal to 0. But, how exactly does it work? I could not work it out.
As already asked: how does sort function work in JavaScript, along with the compare
Share
The “compare” function must take two arguments, often referred to as a and b. Then you make the compare function return 0, greater than 0, or less than 0, based on these values, a and b.
With these three return values, and only two arguments, it is possible to write a compare function that can sort any type of input data type, or complex data structures.
Then, when you call sort(), with your custom compare function, the compare function is called on pairs in your to-be-sorted list, to determine the proper ordering.
Lets walk through a simple example… Suppose you’re only sorting some numbers, so we have a very simple compare function:
Simply subtracting b from a will always return greater than zero if a is larger than b, 0 if they are equal, or less than zero if a is less than b. So it meets the requirements for a compare function.
Now lets suppose this is our list of numbers to sort:
When you call
numbers.sort(compare), internally it will actually execute:If you’ve ever done manual sorting or alphabetizing, you’ve done precisely the same thing, probably without realizing it. Even though you may have dozens or hundreds of items to compare, you’re constantly comparing only two numbers (or author’s last names, or whatever) at a time. Going through or short list of three numbers again, you’d start by comparing the first two numbers:
Because you can provide your own compare() function, it is possible to sort arbitrarily complex data, not just numbers.