window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-63172957-1');
Sound
</html>

Back to blog
JavaScript

# How to Sort Arrays in JavaScript?

Article contents:

In this article, we‟ll 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 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, it‟s 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 &gt; b) return 1;
else if (a &lt; 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, it‟s 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: &quot;home&quot;, x:0, y:0 };

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

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&amp;gt;b.name ? 1 : a.name
);

// library, pub, shops
console.log(map);
```

Or we could sort locations by their shortest distance from any location. First, we‟ll 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:

```&lt;form id=&quot;point&quot;&gt;
X: &lt;input id=&quot;locx&quot; type=&quot;number&quot; /&gt;
Y: &lt;input id=&quot;locy&quot; type=&quot;number&quot; /&gt;
&lt;button&gt;Calculate&lt;/button&gt;&lt;/form&gt;

```

then intercept their form submission and calculate the closest map point:

```var
form = document.getElementById(&quot;point&quot;),
locx = document.getElementById(&quot;locx&quot;),
locy = document.getElementById(&quot;locy&quot;),
output = document.getElementById(&quot;output&quot;);

// intercept form submission
form.onsubmit = function(e) {

// define user's location
var loc = { name: &quot;user&quot;, x: locx.value || 0, y: locy.value || 0 };

// sort
map.sort(
function (a, b) { return Distance(loc, a) - Distance(loc, b); }
);

// output
output.textContent = &quot;Your closest location is the &quot; + map.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. It‟s 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 coordinates, react to the browser window size, etc.

Back to blog

</html> Jack is thinking