It's very common to store numbers and strings in arrays. But what happens if you need to put the numbers in order or arrange the strings alphabetically? The sort() and reverse() methods can be used to achieve the required results. In this topic, you will learn how to use these methods and discover how they work behind the scenes.
Array.sort()
The sort() method puts an array of strings in ascending order by default, but it behaves differently when the array contains numbers.
The below example shows the result of applying sort() to an array of strings:
let fruits = ["Apple", "Banana", "Watermelon", "Grapes", "Pineapple", "Kiwi"];
fruits.sort();
console.log(fruits);
// ['Apple', 'Banana', 'Grapes', 'Kiwi', 'Pineapple', 'Watermelon'];As you can see, the fruits in the array are sorted in alphabetical order as you would expect.
Now let's look at what happens if we apply sort() to an array of numbers:
let numbers = [0, 10, 49, 115, 63, 59, 88, 23];
numbers.sort();
console.log(numbers);
// [0, 10, 115, 23, 49, 59, 63, 88]As shown, the position of several of the numbers has changed, but the array is not sorted in ascending order. So why is this?
By default, the sort() method sorts all elements and values as if they were strings. To be precise, the sort() method converts the elements into strings and then compares them as sequences of UTF-16 code units.
This can lead to some strange results when sorting numbers. For example, 115 is placed before 23 in the above code snippet because "1" comes before "2" in the Unicode order.
To solve this problem, let's deep dive into the sort() method's syntax to discover what else can be accomplished with it.
How sort works
The syntax of the sort() method is as follows:
// Without argument
sort()
// Compare function
sort(compareFunction)
// Arrow function
sort((firstEle, secondEle) => {...})
// Inline function (older syntax)
sort(function compareFunction(firstEle, secondEle) {...})Let's see how the compareFunction works:
function compareFunction(firstEle, secondEle) {
return firstEle - secondEle;
}
let numbers = [0, 10, 49, 115, 63, 59, 88, 23];
numbers.sort(compareFunction);
console.log(numbers); // [0, 10, 23, 49, 59, 63, 88, 115]In this example, we have defined our own function and passed it to the sort() method's optional compareFunction parameter. Now, when sort() compares two values, it sends them to this compareFunction and orders the numbers according to the returned values:
If the return value of the
compareFunctionis less than zero, thefirstEleis sorted before thesecondEle.If the return value is greater than zero, the
secondEleis sorted before thefirstEle.If the return value is zero, the positions of the
firstEleand thesecondEleare not changed.
So, if you need to sort an array of numbers, you can utilize this compareFunction (otherwise known as a comparator function).
It's also possible to use the simpler arrow function syntax (introduced in the ES2015 version of Javascript) to achieve the same result:
let numbers = [0, 10, 49, 115, 63, 59, 88, 23];
numbers.sort((firstEle, secondEle) => firstEle - secondEle);
console.log(numbers); // [0, 10, 23, 49, 59, 63, 88, 115]Array.reverse()
The reverse() method does precisely what you would think — it reverses the order of the elements in an array. This means that the first and last elements are swapped, the second and second-last elements are swapped, and so on.
The below example illustrates how this works:
let arr = ["red", "orange", "blue", "green"];
arr.reverse();
console.log(arr); // ["green", "blue", "orange", "red"]Now, you already know how to sort an array of numbers in ascending order. But what if you want to put them in descending order instead? Fortunately, it's easy to do this by combining what you have learned in this topic:
let numbers = [0, 10, 49, 115, 63, 59, 88, 23];
numbers.sort((firstEle, secondEle) => firstEle - secondEle);
numbers.reverse();
console.log(numbers); // [115, 88, 63, 59, 49, 23, 10, 0]As you can see, the array is first sorted using the arrow function, and then reverse() is applied to place the numbers in the opposite order. It's as simple as that!
Conclusion
You now know that the elements of an array can be ordered alphabetically by using the sort() method without an argument. And you've seen how to put an array of numbers in ascending order by passing a comparator function to sort(). You also discovered that the reverse() method places an array's elements in the opposite order.