Sort array values alphabetically in JavaScript

Introduction

Sorting is one of the most common operations in programming. Arrays can also be sorted.

In JavaScript, the sort() function is used to sort an array. The sort() function can be used in various ways. One of the most common uses of this function is to sort array values alphabetically. Let’s discuss how to use the sort() function in JavaScript to sort array values alphabetically.

Sort() function

The sort() function is invoked using an array. Following is the syntax of sort() function in JavaScript.

array.sort()

By default, the sort() function sorts in ascending order. The sort() function works in two ways:

1. It returns a sorted array.
2. It also sorts the original array.

So, we can either use the sort() function to create a new sorted array or change the positions of the original array. Let’s understand with the help of an example.

let arr = [ 'JavaScript', 'C', 'Python', 'Ruby', 'PHP', 'Swift', 'Java', 'R', 'Go' ];

let sortedArr = arr.sort();

console.log(arr); // [ 'C', 'Go', 'Java', 'JavaScript', 'PHP', 'Python', 'R', 'Ruby', 'Swift' ]

console.log(sortedArr); // [ 'C', 'Go', 'Java', 'JavaScript', 'PHP', 'Python', 'R', 'Ruby', 'Swift' ]

The sort() function is used on array named arr and it is assigned to sortedArr. arr is sorted in ascending order and sortedArr also contains the same sorted array.

To sort an array of strings alphabetically in descending order, we need to pass a function to the sort() function as a parameter. A function passed a parameter to the sort() function can be used in various ways. Let’s create a function to sort the values in descending order.

Observe the following code.

let arr = [ 'JavaScript', 'C', 'Python', 'Ruby', 'PHP', 'Swift', 'Java', 'R', 'Go' ];

arr.sort((x, y) => {
if (x > y)
return -1;
if (x < y)
return 1;
return 0;
});

console.log(arr); // [ 'Swift', 'Ruby', 'R', 'Python', 'PHP', 'JavaScript', 'Java', 'Go', 'C' ]

The function passed to the sort() function as a parameter will sort the values in descending order.

So this is how we are able to sort array values alphabetically in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *