Sorting arrays in Javascript

Let’s suppose we have a simple array containing 5 strings. The .sort() method sorts them in ascending order and the .reverse() method sorts them in descending order, as demonstrated below.

var simpleArray1 = ["Paul", "Peter", "Mary"];

// .sort() will sort the array to become "Mary", "Paul", and then "Peter".
simpleArray1.sort();

// .reverse() will sort the array to become "Peter", "Paul", and then "Mary".
simpleArray1.reverse();

In the case of numbers, we should be aware that they are sorted in a similar fashion as strings. In the following example, 100 appears before 32 when using .sort() because 1 comes before 3.

var simpleArray2 = [100, 999, 32];

// .sort() will sort the array to become 100, 32, and then 999.
simpleArray2.sort();

// .reverse() will sort the array to become 999, 32, and then 100.
simpleArray2.reverse();

To sort an array of numbers by their numeric values, we should pass in a function into the .sort() method as follows.

// .sort(function(a, b) {return a - b}) will sort the array to become 32, 100, and then 999.
simpleArray2.sort(function(a, b) {return a - b});

// .sort(function(a, b) {return b - a}) will sort the array to become 999, 100, and then 32.
simpleArray2.sort(function(a, b) {return b - a});

We can sort an array of objects, ie. each element of the array has its own set of properties, on any of the properties as well. In the following example, each object in the array has a property called “id”, which we are using to sort.

// Ascending order
complexArray.sort(
	function(a, b) {
		return (a.id > b.id ? 1 : (a.id < b.id ? -1 : 0));
	} 
);

// Descending order
complexArray.sort(
	function(a, b) {
		return (a.id > b.id ? -1 : (a.id < b.id ? 1 : 0));
	} 
);

Leave a Reply

Your email address will not be published.