How to sort an array alphabetically in javascript?

📋 Table Of Content
This article is about how to sort an array alphabetically in JavaScript. We will be using the sort() method of JavaScript to sort the elements of the array in ascending or descending order.
The sort()
method of JavaScript allows us to sort elements in an array . It changes the position of the elements in the original array.
By default the
sort()
method sorts the elements of an array in ascending order with the smallest as the first value and largest as the last.
Sort an array alphabetically in Javascript.
Let say we have array of string named countries ,
let countries = ["Uganda", "Sweden", "Thailand", "Zambia", "India", "America"]
And now our task is to sort the countries in alphabetical order, so to do that we will use the sort()
methods as:
let countries = ["Uganda", "Sweden", "Thailand","Zambia", "India", "America"]
const sortedCountries = countries.sort()
console.log(sortedCountries)
OUTPUT:
[ 'America', 'India', 'Sweden', 'Thailand', 'Uganda', 'Zambia' ]
Sort an array alphabetically in descending order
By default the sort() methods sorts the elements in an array alphabetically in ascending order. However to sort it in descending order we have to use the compare
function and pass it in the sort() method.
let countries = ["Uganda", "Sweden", "Thailand","Zambia", "India", "America"]
countries.sort((a, b) => {
if (a > b) return -1;
if (a < b) return 1;
return 0;
});
console.log(countries);
OUTPUT:
[ 'Zambia', 'Uganda', 'Thailand', 'Sweden', 'India', 'America' ]
That's how you can compare and sort alphabets in a array in any order you like.
Related Topics: