How to Sort Arrays in JavaScript

Introduction

JavaScript is the language of the web and is employed in over 90% of websites, along with HTML (Hyper Text Markup Language) and CSS (Cascading Style Sheets).

Arrays in JavaScript are used for storing multiple values under one variable name. These values can be strings, numbers, boolean, undefined, or even another array or object.

const array = [4, "Dog", 100, "cat", true];

In this article, I will be sharing the various methods for sorting arrays in JavaScript.

Sort()

The first place to begin sorting arrays is by using the sort() method. This method sorts the values in ascending order, using Unicode positions/values. The sort() method sorts values as strings. It also modifies the existing array. To avoid array modification, the toSorted() method should be used.

const newArray = ["cat", "rest", "apple", "zoo"];
newArray.sort(); // output: ['apple', 'cat', 'rest', 'zoo']

The above example is pretty straightforward. However, issues arise when numbers are used or the strings are a mixture of uppercase and lowercase letters. In the latter case, it is advisable to convert the strings using toUpperCase() or toLowerCase().

Let us take a look at this code involving numbers.

const numericArray = [25, 100, 60, 3567];
numericArray.sort(); //output: [100, 25, 3567, 60]

As can be seen, the sort() method is inappropriate when dealing with numbers. This brings us to the next method for sorting arrays.

The Compare Function

It is possible to pass a function into the sort() method to get a more accurately sorted array. This function is called the compare function, and the syntax is as follows:

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

The compare function takes two items in the array at a time and sorts them according to the returned value. If the returned value is positive, b is sorted before a. On the other hand, if the value is negative, a is sorted before b. Finally, if the returned value is zero, there is no change to the order of the array items.

Let us take another look at our numericArray and pass the compare function into the sort() method.

const numericArray = [25, 100, 60, 3567];
numericArray.sort(function(a, b) {return a - b}) // output: [25, 60, 100, 3567]

We have now gotten an accurate answer. The compare function is a useful tool for sorting numbers and non-ASCII characters and can also be used for sorting strings.

It is important to note that the compare function can be used to sort arrays in descending order. In this case, the syntax will be function(a, b) {return b - a}.

Sorting Objects Arrays

For arrays that contain objects, the sort() method can be used along with the compare function to compare the values of the object property.

const shoppingList = [
{item: "rice", price: "2000"},
{item: "chocolate", price: "20"},
{item: "water", price: "40"},
]
shoppingList.sort(function(a, b) {return a.price - b.price});
//output: 
//[ 
//{item: 'chocolate', price: '20'},
//{item: 'water', price: '40'},
// {item: 'rice', price: '2000'},
//]

Sorting Sparse Arrays

A sparse array is an array that contains one or more elements with a value of zero. A programmer may want to sort a sparse array to get the specific array elements with values and those without values.

The sort() method, when used on a sparse array, will move the elements with zero values to the end of the array.

const sparseArray = [null, , 56, , "rest", ,false];
sparseArray.sort(); // output: [56, false, null, 'rest', empty × 3]

Conclusion

So far, we have discussed the commonest method of sorting arrays and a method to bypass array modification. We also have the compare function for sorting arrays and sorting sparse and object arrays.