You are on page 1of 4

How to Sort Arrays in JavaScript

In this tutorial, well discuss how you can sort arrays in JavaScript. Sorting an array of values is a key development technique applied in a variety of situations. Consider the following array of integers defined in a JavaScript array:
// define array var myarray = [30, 2, 1, 9, 15];

We can use the standard array sort() method to rearrange the values into logical order:
// sort array myarray.sort(); console.log(myarray);

What result will be output? The result may surprise you. While you would expect [1, 2, 9, 15, 30], the actual output is a seemingly random [1, 15, 2, 30, 9]. The reason is logical once you understand how the sort() method operates. An array may contain numerous types of value; integers, real numbers, strings, objects, etc. When the sort() method is used without a parameter, every value is converted to a string representation and sorted in lexicographic order, e.g. 15 will come before 2 because the first character 1 is lower than 2. Similarly, Banana will appear before apple because an uppercase B is lower than a in the character set.

Comparison Functions
While string comparison has uses, its not the result we need. Fortunately, the array sort() method can be passed a comparison function as a parameter. The comparison function expects two parameters - a and b which are values from the array being sorted. The function must return a numeric value: if a is greater than b, the returned value must be positive (above zero) if a is smaller than b, the returned value must be negative (below zero) if a and b are equivalent, the returned value must be zero

You can therefore define a function to sort an array of numbers from lowest to highest value:

function SortLowToHigh(a, b) { if (a > b) return 1; else if (a < b) return -1; else return 0; }

This can be simplified since subtracting b from a will also return a valid comparison value:
function SortLowToHigh(a, b) { return a b; }

The SortLowToHigh comparison function can be passed to the array sort method:
var myarray = [30, 2, 1, 9, 15]; myarray.sort(SortLowToHigh); console.log(myarray);

Note: do not add () brackets after SortLowToHigh; we are providing a reference to that function rather than calling it. The array is now sorted as we expect: [1, 2, 9, 15, 30].

Inline Functions
If a comparison is used multiple times in your code, its practical to create a named function such as SortLowToHigh above. However, functions in JavaScript are first-class objects and can be used like any other variable. Therefore, if we wanted to sort an array from the highest to lowest value but only required it once in our code, we can pass an anonymous function to the sort() method:
// sort highest to lowest myarray.sort( function(a,b) { return b a; } );

Sophisticated Sorting
The comparison function provides incredible flexibility and we can sort arrays of variables or objects using any criteria. For example, we can define named map locations as objects in an array:

// home co-ordinates var home = { name: "home", x:0, y:0 }; // map co-ordinates var map = [ { name: "shops", { name: "pub", ]; x:3, y:4 }, x:1, y:2 } { name: "library", x:5, y:3 },

Sorting the map array by the object name can be achieved using a comparison function which references that property:
// sort map locations by name map.sort( function (a, b) { return (a.name>b.name ? 1 : a.name<b.name ? -1 : 0); } ); // library, pub, shops console.log(map);

Or we could sort locations by their shortest distance from any location. First, well define a simple function which uses Pythagoras to calculate the distance between two co-ordinate objects:
// distance between two locations function Distance(loc1, loc2) { return Math.sqrt( Math.pow(loc1.x - loc2.x, 2) + Math.pow(loc1.y - loc2.y, 2) ); };

This can then be used within a simple comparison function to determine the closest locations from home (0, 0):
// sort by shortest distance map.sort( function (a, b) { return Distance(home, a) - Distance(home, b); } ); // pub, shops, library console.log(map);

Alternatively, we could permit the user to enter any location in an HTML form:

<form id="point"> X: <input id="locx" type="number" /> Y: <input id="locy" type="number" /> <button>Calculate</button> </form> <p id="output">Please enter your location.</p>

then intercept their form submission and calculate the closest map point:
var form = document.getElementById("point"), locx = document.getElementById("locx"), locy = document.getElementById("locy"), output = document.getElementById("output"); // intercept form submission form.onsubmit = function(e) { // define user's location var loc = { name: "user", x: locx.value || 0, y: locy.value || 0 }; // sort map.sort( function (a, b) { return Distance(loc, a) - Distance(loc, b); } ); // output output.textContent = "Your closest location is the " + map[0].name; // cancel submit e.preventDefault(); return false; };

Summary
At first glance, the array sort() method seems too simplistic for practical use. However, the comparison function is powerful and permits sorting by any criteria. Its just JavaScript code so it can be as complex as you need, e.g. it could load external data using Ajax techniques, compare against geo-location co-ordinates, react to the browser window size, etc. Try writing sort comparison functions in your own projects. Further array lessons and exercises are available in my Learning JavaScript Programming video course.

You might also like