The JavaScript Sort()
method is a built-in function that we can easily use to sort an array of elements in JavaScript. However, the logic and method of applying the sort method differ depending on the data type of the elements in an array (string, number, object, etc.).
This article will teach you how to sort an array for strings, numbers, dates, and objects.
How Does the Sort()
Method Work?
The sort()
method is used to arrange or rearrange the positioning of an element in an array based on a condition.
The sort()
method can arrange digits ranging from -1 to 9, A to Z, a to z, the question is how do we use the sort()
method with digits outside this range, keep reading this will be explained in details.
NOTE: The sort()
method give precedence from -1 to 9, A to Z, a to z. i.e in an array where we have a combination of numbers (-1 to 9), uppercase letter (A - Z), and lowercase letter (a - z), the sort()
method will consider numbers followed by uppercase letter then the lowercase letter.
Why would I need the sort()
method?
The sort method is widely used in many live scenarios.
Below are some of the scenarios where you can use the sort()
method
Imagine an API that returns an array of articles and each article has a key showing number of views, where you need to display the 10 most viewed articles. (sorting by number)
Imagine an array of countries that you need to display in alphabetical order (sorting by string)
Imagine an array of items in a store that you need to display based on when it was added (sorting by date)
Let's get started properly.
How to Sort an Array of Strings in Ascending Order.
Fortunately, the sort()
method, by default, will sort elements in alphabetical order from (a-z). As an outcome, the code below should arrange the string array in ascending order.
//array of strings
const list_of_animals = ["goat", "antelope", "horse", "fox", "cat"];
list_of_animal.sort()
//[ 'antelope', 'cat', 'fox', 'goat', 'horse' ]
How to Sort an Array of Strings in Descending Order
To sort an array of strings in descending order, you must use the reverse()
method with the sort()
method.
The sort() method sorts the array in ascending order, whereas the reverse() method reverses the order of the array elements.
//array of strings
const list_of_animals = ["goat", "antelope", "horse", "fox", "cat"];
list_of_animals.sort().reverse()
//[ 'horse', 'goat', 'fox', 'cat', 'antelope' ]
Note: The above method will work fine where all elements of the array are of the same case (uppercase or lowercase).
However, in the case where the elements in an array include both uppercase and lowercase, we will get an unexpected result.
const list_of_animals = ["goat", "antelope", "Horse", "fox", "Cat"];
list_of_animals.sort()
//[ 'Cat', 'Horse', 'antelope', 'fox', 'goat']
Well, it is not an unexpected result, that is just how the sort()
method works based on precedence, in cases like this all we need to do is convert every element to the same case before applying the sort method. The below code should work fine
const list_of_animals = ["goat", "antelope", "Horse", "fox", "Cat"];
list_of_animals.map((list)=>list.toLowerCase()).sort()
//[ 'antelope', 'cat', 'fox', 'goat', 'horse' ]
Cool, let move to array of numbers
How to Sort an Array of Numbers
Sorting an array of numbers is not as straightforward as that of strings. As stated earlier, the sort method, by default, will sort an array of number ranging from -1 to 9. Therefore applying a sort()
method to an array of numbers will give an unexpected response. For example
//array of numbers
const animal_count = [62, 42, 12, 3, 7];
animal_count.sort()
//[ 12, 3, 42, 62, 7 ]
From the result, you will see that the array sorts based on the first character in each number which is not what we want.
Therefore, to be able to sort an array of numbers, we need an additional comparison function to support the sort()
method.
The compare function will accept two arguments followed by a statement, for instance:
function(x, y) {return x - y}
//The result will be positive if x is greater
//The result will be negative if y is greater
//The result will be zero if x and y are equal
Fortunately, the sort()
method can appropriately sort positive, zero, and negative values.
So, as we use the sort()
method in conjunction with the compare function, the sort()
method compares two values, sends the values to our compare function, and then sorts the values based on the returned value.
How to Sort an Array of Numbers in Ascending Order.
Sorting an array of numbers in ascending order, i.e., from the least number to the highest number
animal_count?.sort((x, y) => x - y);
// 3, 7, 12, 42, 62 ]
How to Sort an Array of Numbers in Descending Order
We are sorting an array of numbers in descending order, i.e., from the highest number to the least number.
animal_count?.sort((x, y) => y - x);
// [ 62, 42, 12, 7, 3 ]
How to Sort an Array of Dates in Ascending Order
Sorting an array of dates in ascending order, i.e., from the least date to the highest date
const date_added = ["2022-07-15T17:10:57.720274+01:00", "2022-07-15T17:12:57.720274+01:00", "2022-07-14T17:10:00.720274+01:00", "2022-07-13T17:09:57.720274+01:00", "2022-07-15T17:10:50.720274+01:00"];
date_added?.sort((x, y) => new Date(x) - new Date(y));
/* [
'2022-07-13T17:09:57.720274+01:00',
'2022-07-14T17:10:00.720274+01:00',
'2022-07-15T17:10:50.720274+01:00',
'2022-07-15T17:10:57.720274+01:00',
'2022-07-15T17:12:57.720274+01:00'
] */
How to Sort an Array of Dates in Descending Order
Sorting an array of dates in ascending order, i.e., from the highest date to the last date:
const date_added = ["2022-07-15T17:10:57.720274+01:00", "2022-07-15T17:12:57.720274+01:00", "2022-07-14T17:10:00.720274+01:00", "2022-07-13T17:09:57.720274+01:00", "2022-07-15T17:10:50.720274+01:00"];
date_added?.sort((x, y) => new Date(y) - new Date(x));
/*[
'2022-07-15T17:12:57.720274+01:00',
'2022-07-15T17:10:57.720274+01:00',
'2022-07-15T17:10:50.720274+01:00',
'2022-07-14T17:10:00.720274+01:00',
'2022-07-13T17:09:57.720274+01:00'
]*/
How to Sort an Array of Objects by Any Key Value
Considering the below array of objects, we can sort by any of the keys (id
, name
, count
, date_added
) based on what you have learned in this article. However, I will show you how to sort by date_added
and by name
:
//array of object
const activity_history = [
{
id: "1",
name: "goat",
count: 62,
date_added: "2022-07-15T17:10:57.720274+01:00"
},
{
id: "2",
name: "antelope",
count: 42,
date_added: "2022-07-15T17:12:57.720274+01:00"
},
{
id: "3",
name: "horse",
count: 12,
date_added: "2022-07-14T17:10:00.720274+01:00"
},
{
id: "4",
name: "fox",
count: 3,
date_added: "2022-07-13T17:09:57.720274+01:00"
},
{
id: "5",
name: "cat",
count: 7,
date_added: "2022-07-15T17:10:50.720274+01:00"
}
];
How to Sort an Array of Objects by Date in Ascending Order
activity_history?.sort(
(x, y) => new Date(x.date_added) - new Date(y.date_added)
);
How to Sort an Array of Objects by Date in Descending Order
activity_history?.sort(
(x, y) => new Date(y.date_added) - new Date(x.date_added)
);
How to Sort an Array of Objects by Name in Ascending Order
activity_history.sort((x, y)=>{
if(x.name < y.name) { return -1; }
if(x.name > y.name) { return 1; }
return 0;
})
How to Sort an Array of Objects by Name in Descending Order
activity_history.sort((x, y)=>{
if(y.name < x.name) { return -1; }
if(y.name > x.name) { return 1; }
return 0;
})
Conclusion
Ooh yeah, that is it. I hope you learned and understand how easy it is to use the sort()
method for different data types through the many examples of how the methods work.
Thanks for Reading 🌟🎉
I'd love to connect with you on Twitter
Happy coding!
Top comments (2)
map
returns a copy of the original array so you need to assign the result back tolist_of_animals
.Or you could compare lowercase strings in the sort method.
you should at least do the following: