How to Sort Array Alphabetically in JavaScript

Sorting an array in alphabetical order is a common task for JavaScript developers.

Whether it’s sorting a list of names or sorting a list of products, the process is straightforward.

In this Javascript tutorial, we’ll explore different methods to sort an array in JavaScript alphabetically and provide code examples to help you get started.


Array.sort() Method

The Array.sort() method is a simple and straightforward way to sort an array in JavaScript.

By default, the sort method sorts the array in lexicographic (alphabetical) order.

The method can be used as follows:

let names = ['John', 'Jane', 'Jim', 'Jenny'];
names.sort();
console.log(names); // ['Jane', 'Jim', 'Jenny', 'John']

Custom Sorting Function

If you need to sort an array in a specific order, you can use a custom sorting function.

The function should return a negative, zero, or positive value, depending on the arguments, like:

let numbers = [5, 1, 4, 2, 8];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers); // [1, 2, 4, 5, 8]

Here’s an example of a custom sorting function for sorting an array of names in reverse alphabetical order:

let names = ['John', 'Jane', 'Jim', 'Jenny'];
names.sort(function(a, b) {
  if (a < b) {
    return 1;
  }
  if (a > b) {
    return -1;
  }
  return 0;
});
console.log(names); // ['John', 'Jenny', 'Jim', 'Jane']

Array.prototype.sort()

In addition to the sort method, JavaScript also has a sort function on the Array.prototype object.

This function allows you to sort an array in place, without creating a new sorted array.

Here’s an example of using the sort function to sort an array of numbers:

let numbers = [5, 1, 4, 2, 8];
Array.prototype.sort.call(numbers, function(a, b) {
  return a - b;
});
console.log(numbers); // [1, 2, 4, 5, 8]

Conclusion

In conclusion, sorting an array in alphabetical order in JavaScript is a simple task that can be accomplished using the Array.sort() method or a custom sorting function.

Whether you’re sorting a list of names or sorting a list of products, these methods can help you get the job done.

I hope this tutorial has been helpful in your journey to become a better JavaScript developer.