# Sorting out JavaScript Array Sorting

JavaScript

Share:

😳 Ever felt a little embarassed sharing your JavaScript? Let's fix it.

Consider the following JavaScript code:

`var a = [30,2,1,9,15];a.sort();alert(a);`

What would be output?If you’re expecting 1,2,9,15,30, you’ll be surprised to hear the actual result is 1,15,2,30,9. Don’t give up on JavaScript just yet; array sorting is incredibly powerful once you know how to use it.So what’s going on? When nothing is passed to the sort method, every value is converted to a string and sorted in lexicographic order, i.e. “15” will come before “2”. So will “10” and “19999999”.To fix the problem, we need to pass a comparison function to the sort() method. The function must take 2 parameters — we’ll name them a and b — and return:

- a value less than zero if a is less than b
- a value greater than zero if a is greater than b
- zero if a and b are equal

The simplest numeric compare function is therefore:

`function compare(a, b) { return a - b;}`

We can pass the compare function as as argument for the sort method or write it inline, e.g.

`var a = [30,2,1,9,15];a.sort(function(a,b) { return a-b; });alert(a);`

The output is now a far more logical 1,2,9,15,30.One of the great things about JavaScript is that our comparison functions can sort any type of object by any property. For example, we’ll define a list of locations and home co-ordinates:

`// location co-ordinatesvar locations = [ { name: "shops", x:3, y:4 }, { name: "library", x:5, y:3 }, { name: "pub", x:1, y:2 }];// home co-ordinatesvar home = { name: "home", x:0, y:0 };`

Next, we’ll add a little Pythagoras to a function which calculates the distance between two points:

`// distance between 2 co-ordinatesfunction distance(p1, p2) { return Math.sqrt(Math.pow(p1.x-p2.x,2)+Math.pow(p1.y-p2.y,2));}`

We can now sort the locations by distance from home — shortest to the furthest trip:

`// sort by shortest distance homelocations.sort( function(a, b) { return distance(home,a)-distance(home,b); });// locations sorted: pub, shops, library`

Or we could sort by furthest to shortest distance by reversing the parameters:

`// sort by furthest distance homelocations.sort( function(b, a) { return distance(home,a)-distance(home,b); });// locations sorted: library, shops, pub`

Or we can order location names alphabetically:

`locations.sort( function(a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; });// locations sorted: library, pub, shops`

It’s easy to develop a range of reusable sorting functions which can be applied to any object containing similar property names. In that respect, JavaScript sorting is easier and more flexible than many other languages.

**note:**Want more?

If you want to read more from Craig, subscribe to our weekly tech geek newsletter, *Tech Times*.