Photo by Crissy Jarvis on Unsplash
Understanding the sort() method in JavaScript
Think like an engineer
Take a look at some of the most viewed questions on Stack Overflow and you will quickly realize that they are not niche or incredibly complex topics. And while it may be tempting to assume that only absolute beginners are searching for those answers, this isn't necessarily true.
A common bit of advice that new programmers will hear is, "Don't worry about memorizing syntax". And to be sure, this is solid advice. At a certain point however, your aim should be to have such a solid understanding of the fundamentals, that you can reason your way to a solution rather than relying on memorized syntax, or a StackOverflow search for a basic question.
To illustrate an example of how we can accomplish this, let's take a look at the JavaScript sort()
method.
Many beginners do have a relatively hazy, but mostly understanding of what this method accomplishes. But let's unambiguously define and describe exactly what this method does.
The sort()
method is a built-in function in JavaScript that allows you to sort arrays of values in place. It sorts the elements of an array in ascending or descending order, depending on how you call it.
When you call the sort()
method without any arguments, it will sort the array elements in ascending order using the Unicode values of the elements. This means that if you sort an array of numbers using sort()
, it will not sort them according to their actual size, but rather according to their Unicode character code.
For example, if you have an array of numbers [10, 5, 20, 2]
and you sort it using the sort()
method, the result will be [10, 2, 20, 5]
. This is because the sort method is using the Unicode character codes of the numbers rather than their actual values.
To sort an array of numbers in JavaScript in numerical order, you need to pass a comparison function to the sort()
method. This function will be used to determine the order in which the elements should be sorted. The comparison function takes two arguments, a
and b
, which represents two elements being compared. It returns a negative number if a
should come before b
, a positive number if b
should come before a
, and zero if they are equal.
Here's an example of how to sort an array of numbers using a comparison function:
const numbers = [10, 5, 20, 2];
numbers.sort((a, b) => a - b);
console.log(numbers); // [2, 5, 10, 20]
In this example, the comparison function a - b
is used to sort the numbers in ascending order. If you wanted to sort them in descending order, you could use the comparison function b - a
instead.
Understanding how a built-in method works is always great, but understanding how to replicate the functionality of a method with your code is even better for solidifying your knowledge.
So if, for example, you wanted to sort an array of numbers without using the sort
method and comparison function, how would we accomplish that? Let's examine the obvious without code first:
We wish to intake an array of digits that are ostensibly unsorted.
The goal is to arrange the digits in the array from smallest to largest.
Creating a function that takes advantage of a Bubble sort algorithm should allow us to accomplish this.
function mySort(array) {
let swapped;
do {
swapped = false;
for (let i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return array;
}
Here is a step-by-step breakdown of the function:
The function
mySort
takes an unsorted array as an argument.It initializes a variable called
swapped
tofalse
.It enters a
do-while
loop which runs at least once and continues to run as long as the value ofswapped
istrue
.Inside the
do-while
loop, the function loops through each element in the array using afor
loop.For each element in the array, it checks if it is greater than the next element in the array.
If the current element is greater than the next element, then it swaps the positions of these two elements.
It sets the value of
swapped
totrue
if any swap occurs in the loop.The
do-while
loop continues until no more swaps are needed, which means the array is sorted.Finally, the sorted array is returned by the function.
Overall, this function implements the bubble sort algorithm to sort an array in ascending order. The bubble sort algorithm works by repeatedly comparing adjacent elements in the array and swapping them if they are in the wrong order. The algorithm continues until no more swaps are needed, which means the array is sorted.
Hopefully with a better understanding of how the sort
method works, and by gaining an understanding of an alternate way to implement it, you can apply that knowledge to other small aspects of your learning journey.
Think like an engineer.