This post will discuss how to sort an array of integers in JavaScript.

There are several ways to sort an array of integers in JavaScript. Here are some examples of how to sort an array of integers in JavaScript given an array:

1. Using a compare function

This is a common technique that works in any version of JavaScript. It involves passing a custom compare function to the Array.sort() function, which defines how to compare two elements in the array. The compare function should return a negative, zero, or positive value, depending on whether the first element is less than, equal to, or greater than the second element. For example, if we have an array and we want to sort it in ascending order, we can do:

Download  Run Code

 
To sort an array in reverse order, we can return the opposite of what we would return for ascending order. Here’s an example:

Download  Run Code

2. Using ES6 arrow function

The arrow function is a newer feature of JavaScript that allows writing concise functions with a shorter syntax. It involves using an arrow (=>) to define a compare function for the Array.sort() function. We can use the same logic as the previous example, but with a simpler syntax. Here’s an example:

Download  Run Code

 
To sort an array in reverse order, we can compare two elements by subtracting them in reverse order. For example,

Download  Run Code

3. Using Intl.Collator object

This is another newer feature of JavaScript that allows sorting arrays according to the language and locale settings. It involves creating an instance of the Intl.Collator object with the desired options and using its compare function as the compare function for the Array.sort() function. For example, if we have an array and we want to sort it in ascending order according to the German numeric format (which uses a comma as the decimal separator), we can do:

Download  Run Code

That’s all about sorting an array of integers in JavaScript.