While coding programs we often encounter the task of putting things in order, i.e. sorting, there will always be a situation in real life where we have to sort things alphabetically. In this article, we will how to sort arrays alphabetically in JavaScript. So, let’s get started!
How to Sort Alphabetically in JavaScript?
The built-in sort() method in JavaScript is used to sort arrays alphabetically in JavaScript. This function sorts in ascending order by default.
However, we can customize it using a compare function () according to our needs.
It is written as:
array.sort()
This method directly works when we have to sort an array of strings but not on an array of objects, because in that case, we have to manually tell the location of the string in the object.
Sorting an Array of Strings
As the sort() method sorts in ascending order, we can pass a compareFunction() with it if we want to sort in any other way, basically compareFunction() defines the criteria for ordering.
The sort () method places uppercase letters before lowercase, therefore in a situation where some strings start with uppercase while some with lowercase, the output will be incorrect.
Let’s take an example of failed sorting and then we will learn how to correct it:
// Given array of fruits with mixed case const fruits = ['Apple', 'Banana', 'orange', 'GrapE', 'kiwi']; // Incorrectly sorting the array using sort() fruits.sort(); // Print results console.log(fruits);
Output:
['Apple', 'Banana', 'GrapE', 'kiwi', 'orange']
We can see sorting is not as we desired, therefore for case-in-sensitive sorting, we will first of all convert all the strings to lowercase. We will use the toLowerCase() method inside our compareFunction, which converts the whole string to lowercase.
CompareFunction is written as :
array.sort(compareFunction);
This compareFunction takes two parameters in it. Let it be x and y. These are the two values we are comparing. It returns a negative, zero, or positive value based on arguments passed.
If ‘x’ should be placed before ‘y’ it returns a negative value, in the case of a positive value ‘x’ is placed after ‘y’, and zero is returned if ‘x’ and ‘y’ are of the same order.
Let’s modify our previous code and perform sort() once again:
// Given array of fruits with mixed case const fruits = ['Apple', 'Banana', 'orange', 'GrapE', 'kiwi']; // Correctly sorting the array using a custom comparison function fruits.sort((x, y) => { // Convert both strings to lowercase for case-insensitive comparison const lowercaseX = x.toLowerCase(); const lowercaseY = y.toLowerCase(); // Compare the lowercase versions of strings if (lowercaseX < lowercaseY) { return -1; // Return a negative value if x should come before y } else if (lowercaseX > lowercaseY) { return 1; // Return a positive value if x should come after y } else { return 0; // Return 0 if x and y are equal } }); // Print results console.log(fruits);
Output:
['Apple', 'Banana', 'GrapE', 'kiwi', 'orange']
First of all, we converted our names into lowercase to ensure case-in-sensitive sorting. Then we returned -1,1 or 0 based on comparisons. More appropriately we returned -1 if ‘x’ should be placed before ‘y’,1 if ‘x’ should be placed after ‘y’, and 0 if no change.
Sorting an Object Alphabetically
We can’t apply the sort() method directly on an object. We will first tell this function the location of the string inside the object, according to which we want to sort.
As we know an object is a collection of different properties. Here we need to access the string property inside the object. Properties inside an object can be accessed using the dot notation. It is written as:
object.propertyName
Let’s take an example of an array of objects named ‘people’. It contains the names, ages, and occupations of different persons encapsulated within it. We will sort according to their names in ascending order with the help of a compareFunction.
// array of objects const people = [ { name: 'Alice', age: 30, occupation: 'Engineer' }, { name: 'bob', age: 25, occupation: 'Designer' }, { name: 'Charlie', age: 35, occupation: 'Developer' }, { name: 'dave', age: 28, occupation: 'Analyst' } ]; // Sorting the array of objects by names people.sort((person1, person2) => { // Convert names to lowercase for case-insensitive sorting const lowercaseName1 = person1.name.toLowerCase(); const lowercaseName2 = person2.name.toLowerCase(); // Compare the lowercase versions of names if (lowercaseName1 < lowercaseName2) { return -1; // Return a negative value if person1 should come before person2 } else if (lowercaseName1 > lowercaseName2) { return 1; // Return a positive value if person1 should come after person2 } else { return 0; // Return 0 if names are equal } }); //print results console.log(people);
Output:
[
{ name: 'Alice', age: 30, occupation: 'Engineer' },
{ name: 'bob', age: 25, occupation: 'Designer' },
{ name: 'Charlie', age: 35, occupation: 'Developer' },
{ name: 'dave', age: 28, occupation: 'Analyst' }
]
So we have successfully sorted them according to their names. First of all, we converted our names into lowercase to ensure case-in-sensitive sorting. Then we returned -1,1 or 0 based on comparisons. More appropriately we returned -1 if ‘x’ should be placed before ‘y’,1 if ‘x’ should be placed after ‘y’, and 0 if no change.
We can also change this compareFunction to sort according to names in descending order. Let’s see how:
// Given array of people with names, ages, and occupations const people = [ { name: 'Alice', age: 30, occupation: 'Engineer' }, { name: 'bob', age: 25, occupation: 'Designer' }, { name: 'Charlie', age: 35, occupation: 'Developer' }, { name: 'dave', age: 28, occupation: 'Analyst' } ]; // Sorting the array of objects by names in descending order people.sort((person1, person2) => { // Convert names to lowercase for case-insensitive sorting const lowercaseName1 = person1.name.toLowerCase(); const lowercaseName2 = person2.name.toLowerCase(); // Compare the lowercase versions of names in descending order if (lowercaseName1 > lowercaseName2) { return -1; // Return a negative value if person1 should come before person2 } else if (lowercaseName1 < lowercaseName2) { return 1; // Return a positive value if person1 should come after person2 } else { return 0; // Return 0 if names are equal } }); //print results console.log(people);
Output:
[
{ name: 'dave', age: 28, occupation: 'Analyst' },
{ name: 'Charlie', age: 35, occupation: 'Developer' },
{ name: 'bob', age: 25, occupation: 'Designer' },
{ name: 'Alice', age: 30, occupation: 'Engineer' }
]
Here simply we have reversed the logic, we have returned -1 if ‘x’ is bigger than ‘y’ i.e. if x should be placed before y. In the case of a positive value ‘x’ is placed after ‘y’ i.e. is smaller than ‘y’, and zero is returned if ‘x’ and ‘y’ are of the same order.
Conclusion
We have learned how to sort alphabetically in JavaScript by using the sort() method and a compareFunction. Now we are ready to organize our data in the desired order. There are also other ways of sorting as well, you can learn how to Sort an array of Objects in JavaScript.