JavaScript Sorting Arrays
Falah Al Fitri
Posted on December 23, 2021
Array
The sort()
method sorts an array alphabetically:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Apple,Banana,Mango,Orange
The reverse()
method reverses the elements in an array.
You can use it to sort an array in descending order:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse(); // Orange,Mango,Banana,Apple
Numeric Sort
By default, the sort()
function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort()
method will produce incorrect result when sorting numbers.
You can fix this by providing a compare function:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort( (a, b) => (a - b) ); // 1,5,10,25,40,100
Use the same trick to sort an array descending:
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort( (a, b) => (b - a) ); // 100,40,25,10,5,1
💖 💪 🙅 🚩
Falah Al Fitri
Posted on December 23, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Mastering JavaScript Arrays: Techniques, Best Practices, and Advanced Uses
September 3, 2024