When talking about JavaScript and working with arrays, one of the most common and well-known methods is to use the sort()
function. This method arranges the elements of an array based on a specific condition, allowing for custom or previously defined sorting.
In the real world, array sorting can be used for data listing, displaying data to the user, or sorting lists like grades or user rankings. In this section, with several simple examples and sufficient explanations, we will familiarize you with the working method of this function.
First, let’s take a look at how the sort()
function operates in its simplest form. This function, by default, sorts numbers in a Lexicographical order (dictionary style), which may sometimes not be what is expected. For instance, if the array contains [3, 12, 1], the result would be [1, 12, 3], which might not be the expected outcome. In this case, we need to create a custom array sorting function.
Using the custom sorting function gives you the capability to change the data based on your own needs for sorting. In this way, you can utilize a compare
function to determine the order of the elements. This function accepts two parameters and allows you to compare them. The result of the comparison can specify the order of the elements.
In the continuation, we will provide a practical example of sorting numerical elements in ascending order to familiarize you. Likewise, we will also analyze the descending order. These examples will assist you in finding appropriate solutions for different scenarios.
JavaScript Code Example for Array Sorting
const numbers = [40, 100, 1, 5, 25, 10];
// Sorting from smallest to largest
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 5, 10, 25, 40, 100]
// Sorting from largest to smallest
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [100, 40, 25, 10, 5, 1]
Line by Line Explanation of the Above Code:
const numbers = [40, 100, 1, 5, 25, 10];
This line creates an array of different numbers named numbers
.
numbers.sort((a, b) => a - b);
This line calls the sort()
function, which will execute with a custom compare
function. The difference between the two numbers is analyzed. If the first number is smaller, it returns a negative value, which causes a swap.
console.log(numbers); // Output: [1, 5, 10, 25, 40, 100]
This line will print the sorted array in ascending order to the console.
numbers.sort((a, b) => b - a);
Again, the sort()
is used, but this time, the parameters b
and a
are reversed for descending order sorting.
console.log(numbers); // Output: [100, 40, 25, 10, 5, 1]
This line will print the sorted array in descending order to the console.