Categories:

Sorting an array in numerical order

For the most part, sorting numerical values means you want them sorted numerically. JavaScript understands that, and in a while, you will understand how to.

Sorting an array in numerical order still involves the same sort() method, with a little twist:

arrayname.sort(functionname)

"functionname" represents the returned value of a special function created specifically for the sort() method. A function like this has the following format:

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

Lets first put all this together and sort an array numerically, before anything else:

function sortit(a,b){
return(a-b)
}
var myarray=new Array(70,43,8)
myarray.sort(sortit)  
//myarray[0] is now 8, myarray[1] is now 43, myarray[2] is now 70

Ok, so what's "a" and "b", and why all this weird additional syntax? Well, "a" and "b" are two imaginary values the sort() method uses to determine how to sort an array. Subtracting "b" from "a"  indicates to the sort() method that we want it to sort the array numerically.