How to sort an array in JavaScript?

JavaScript

Sorting is one of the most significant issues in programming. Whether you are a beginner or a veteran developer, you will face sorting algorithms in your exams or job interviews. 

Luckily in real-life scenarios, we don’t need to implement any sorting algorithms from scratch. JavaScript has its own build-in sorting methods and in this article, we will cover how to sort an array in JavaScript.

Let’s start with the Sorting Algorithm concept.

What is a Sorting Algorithm?

According to Wikipedia;

In computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most frequently used orders are numerical order and lexicographical order.

For our specific case, a sorting algorithm mostly deals with array elements in terms of sorting their order alphabetically or numerically by changing the position of each element in the array. The sorting can happen ascending or descending based on your preference.

For example, we have an array below with unordered alphabetic characters:

let myAlphabeticArray = ['d', 'a', 'b', 'c'];

If your preference is to sort them in ascending order, the correct result is:

['a', 'b', 'c', 'd']

If your preference is to sort them in descending order, the correct result is:

['d', 'c', 'b', 'a']

We can also do the same thing for an unordered array with numbers:

let myNumericArray = [4,1,3,2]; 

If your preference is to sort them in ascending order, the correct result is:

[1,2,3,4]

If your preference is to sort them in descending order, the correct result is:

[4,3,2,1]

It’s a piece of cake! But in order to implement any sorting algorithm from scratch, you need to learn a few types of sorting algorithms.

Types of Sorting Algorithms

The most common sorting algorithms are 

  • Bubble sort
  • Selection sort
  • Insertion sort
  • Merge sort
  • Quicksort
  • Heap Sort

In this article, we will not cover them but you can find those algorithms easily by googling. 

In order to apply those algorithms correctly based on your programming language preference, you should know how to deal with arrays in that specific language. 

For our case, we are using JavaScript and If you don’t know much about JavaScript arrays, feel free to read our other post about JavaScript arrays.

Thanks to JavaScript, we already have predefined array sorting methods.

JavaScript Array sorting methods

Whenever you define an array, it will have a publicly accessible sort() and reverse() methods and just like any public method, these methods can be called through your array variable with dot notation.

Let’s look at these methods.

The sort() method

If you want to order an array in ascending order, you should use the sort() method: 

let myAlphabeticArray = ['d', 'a', 'b', 'c'];
myAlphabeticArray.sort(); // output is ['a', 'b', 'c', 'd']

The reverse() method

If you want to sort your array in descending order, you can use the reverse method.

myAlhabeticArray.reverse(); // output is ['d', 'c', 'b', 'a']

In JavaScript Arrays are mutable and also, the sort() and reverse() methods are implemented in a mutable way. That’s is why by running these methods, the array content will be changed and you will lose the previous state of your array.

You can also test these sort() and reverse() methods on a numeric array, and for our example, you can get the results as below:

let myNumericArray = [4, 1, 3, 2];
myNumericArray.sort(); // output is [1, 2, 3, 4]
myNumericArray.reverse(); // output is [4, 3, 2, 1]

But there is a big WARNING!

If you think that we also can use these methods on numeric arrays safely, you will be in big trouble.

Because by default these sort and reverse methods compare and order each array element alphabetically. Even if your array has numeric values, it doesn’t matter, it automatically behaves all array elements as string values. 

Sorting Array Alphabetically (Default Behavior)

For example, this time you have a different numeric array and we use the same methods to sort it.

let myWillNotWorkExpectedlyArray = [3, 10, 1, 20];

myWillNotWorkExpectedlyArray.sort(); 
// output is [1, 10, 20, 3]

myWillNotWorkExpectedlyArray.reverse(); 
// output is [3, 20, 10, 1]

You will get these weirdly ordered arrays. 

Also, you can try another mixed array:

let myAnotherWillNotWorkExpectedlyArray = ['a', 'A', 1, '!'];

myAnotherWillNotWorkExpectedlyArray.sort() 
// output is ['!', 1, 'A', 'a'];

myAnotherWillNotWorkExpectedlyArray.reverse() 
// output is [‘a’, ‘A’, 1, ’!’];

Again the result will not have a logical explanation at the first look.

WHY? 

Because as I mentioned before by default sort() and reverse() methods are comparing array elements alphabetically, whether the array elements are numeric or string. 

But this alphabetic comparison actually is a string comparison and it is ordering them based on their Unicode codes.

Unicode is an encoding standard to handle characters in the computing industry. You can get this Unicode character code list from https://en.wikipedia.org/wiki/List_of_Unicode_characters.

In order to see the order of these characters, let’s look at the order of the Unicode codes of commonly used characters from the below graph.

The character order is starting from the top left corner and continues to the right corner from the left to right.

According to this Unicode order table, we can make some inferences about this alphabetic sort behavior as:

  1. Numbers always have the first order compared to alphabetic characters.
  2. Lowercase alphabetic characters always have the last order compared to the capital alphabetic characters.

For other nonalphanumeric characters, you need to check the Unicode order table because some notations are before the numeric characters, between the capital and lowercase alphabetic characters, or the last in the list.

Ok so now we know the default behavior of sorting methods in JavaScipt but what about sorting the numeric arrays?

Sorting Array Numerically

In order to sort arrays numerically, we just need to pass a parameter to the sort() or reverse() method. 

This parameter is needed to be a function that should compare just two elements. Thanks to that we can override the sort() and reverse() methods default comparison logic. 

In our case, we want to make this logic a numeric comparison but don’t forget that we can also apply a custom comparison logic.

Let me tell you about this compare function implementation generally.

  1. The function should take two parameters.
  2. If you think the first parameter should be before the second parameter return a negative number.
  3. If you think the first parameter should be after the second parameter return a positive number bigger than zero.
  4. If you think two parameters are equal or there is no need to take any action just return number zero.

For numeric comparison, we just need to compare two numbers. If we implement this function precisely based on the algorithm above, the function will be:

function numberComparator(firstNumber, secondNumber) {
  if(firstNumber < secondNumber) return -1;
  else if(firstNumber > secondNumber) return 1;
  else return 0;
}

But the shorter implementation with the same logic can be:

function numberComparator(firstNumber, secondNumber) {
  return firstNumber - secondNumber;
}

Now we can pass our custom compare function to the sort() and reverse() method as:

let myWillWorkExpectedlyArray = [3, 10, 1, 20];

myWillNotWorkExpectedlyArray.sort(numberComparator); 
// output is [1, 3, 10, 20]

myWillNotWorkExpectedlyArray.reverse(numberComparator); 
// output is [20, 10, 3, 1]

As you can see now our sort() and reverse() methods can sort numeric arrays correctly. 

By passing our custom comparator function, we override its default alphabetic comparison behavior. 

By the way, clearer and more suitable implementation in ES6 JavaScript should be:

let myWillWorkExpectedlyArray = [3, 10, 1, 20];

myWillNotWorkExpectedlyArray.sort(() => firstNumber - secondNumber)); 
// output is [1, 3, 10, 20]

myWillNotWorkExpectedlyArray.reverse(() => firstNumber - secondNumber)); 
// output is [20, 10, 3, 1]

So now we know how to sort alphabetic or numeric array elements but you may be curious about which sorting algorithm is used when sort() and reverse() methods are called.

Which sorting algorithm is used in JavaScript?

You may already know that JavaScript can be run on lots of different environments as client-side or server-side. Also, these environments can have different JavaScript engines like V8, Chakra, SpiderMonkey that are the only popular ones. 

  • V8 which is used in mostly Google Chrome and Node.js. 
  • Chakra is a Microsoft product that is used in Microsoft Edge.
  • SpiderMonkey is the JavaScript engine used in Firefox Browser. 

Each of these engines has its own architecture and JavaScript interpretation logic. Thus sort() and reverse() methods are not using a common sorting algorithm on different platforms. 

But according to the various resources, they are mostly using Insertion sort, Selection sort, Merge sort, or Quicksort interchangeably based on the array size.

Conclusion 

I hope now you can use sort() and reverse() methods for sorting numeric or alphabetic arrays without any hesitation.

If you want to learn more about Web Development, don’t forget to subscribe to our newsletter and if you have any questions, please don’t hesitate to contact me.

See you in new articles.

Leave a Reply

Your email address will not be published. Required fields are marked *