Coffee - 1 month ago 5x
Javascript Question

# How does the JavaScript sort function work(as an algorithm)?

The JavaScript sort function which takes a parameter allows one to pass in a function.

For example:

var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return a - b}) //Array now becomes [7, 8, 25, 41]

How is it that the code

function(a,b){
return a - b
}

is interpreted to be ascending? It's supposed to be divided into three cases,
< 0
,
== 0
, and
> 0
, but how does this make sense when
a
and
b
can be anything?

Thank You!

Answer

The reason answering your question is especially tricky, or at least in detail, is because there is no specification that says which sorting algorithm a browser should implement. So telling you specifically how it works on one browser may differ between browsers, or even change over time.

The gist of it is though, you want to think of "a" and "b" as being any two values. If you are returning the result of "a" - "b", then your sort goes in ascending order. If you do "b" - "a", then it is in descending order.

The neat thing about making your own sort functions, is that you can compare the value of "a" and "b" after processing them in a separate function. So lets say you want to sort by the Celsius values, but your array in only in Fahrenheit. You can do something like:

.sort(function(a,b){ return to_fahrenheit(a) - to_fahrenheit(b);}
Comments