How to Sort an Array Alphabetically in TypeScript?

If you are working as a TypeScript developer, you are often required to sort an array alphabetically. There are various methods to do it. In this tutorial, I will explain how to sort an array alphabetically in TypeScript.

Sort an Array Alphabetically in TypeScript

Sorting arrays alphabetically can improve the readability and usability of your TypeScript application. For instance, if you display a list of cities or names, an alphabetical order allows users to find what they’re looking for quickly and efficiently. Additionally, sorted data can enhance the overall user experience by providing a structured and organized presentation.

TypeScript, being a superset of JavaScript, inherits all the array manipulation methods from JavaScript, including the powerful sort() method. The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts the elements as strings in ascending order.

Now, let me show you some examples of sorting an array alphabetically in TypeScript.

Example: Sort an Array of Strings Alphabetically

Let’s start with a basic example of sorting an array of city names alphabetically in TypeScript:

const cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];

cities.sort();

console.log(cities);

In this example, the cities array will be sorted alphabetically, resulting in:

["Chicago", "Houston", "Los Angeles", "New York", "Phoenix"]

You can see the exact output in the screenshot below:

Sort an Array Alphabetically in TypeScript

Check out Sort String Arrays in TypeScript

Sorting with Custom Comparison

The default sort() method in TypeScript works well for simple string arrays, but what if you need to sort an array of objects based on a specific property? This is where a custom comparison function comes into play.

Sorting an Array of Objects

Consider an array of objects representing a list of people, each with a firstName and lastName property. We want to sort this array alphabetically by the lastName property.

Example: Sort by Last Name

Now, let me show you an example of how to sort by last name in TypeScript.

interface Person {
  firstName: string;
  lastName: string;
}

const people: Person[] = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Jane", lastName: "Smith" },
  { firstName: "Michael", lastName: "Johnson" },
  { firstName: "Emily", lastName: "Davis" },
  { firstName: "David", lastName: "Brown" }
];

people.sort((a, b) => a.lastName.localeCompare(b.lastName));

console.log(people);

In this example, the localeCompare method is used to compare the lastName properties of the Person objects. The sorted array will be:

[
  { firstName: "David", lastName: "Brown" },
  { firstName: "Emily", lastName: "Davis" },
  { firstName: "John", lastName: "Doe" },
  { firstName: "Michael", lastName: "Johnson" },
  { firstName: "Jane", lastName: "Smith" }
]

You can see the exact output in the screenshot below:

TypeScript Sort an Array Alphabetically

Example: Sort by First Name

Similarly, if you want to sort the array by the firstName property, you can modify the comparison function accordingly:

people.sort((a, b) => a.firstName.localeCompare(b.firstName));

console.log(people);

The sorted array by firstName will be:

[
  { firstName: "David", lastName: "Brown" },
  { firstName: "Emily", lastName: "Davis" },
  { firstName: "Jane", lastName: "Smith" },
  { firstName: "John", lastName: "Doe" },
  { firstName: "Michael", lastName: "Johnson" }
]

Check out Sort an Array of Objects by Property Value in TypeScript

Handle Case Sensitivity While Sorting in TypeScript

By default, the localeCompare method is case-sensitive, which means “apple” and “Apple” will be treated differently. If you want to perform a case-insensitive sort, you can convert the strings to lowercase (or uppercase) before comparing them.

Example: Case-Insensitive Sorting

people.sort((a, b) => a.firstName.toLowerCase().localeCompare(b.firstName.toLowerCase()));

console.log(people);

This approach ensures that the sorting is case-insensitive, treating “John” and “john” as equal.

Sort with Multiple Criteria

Sometimes, you might need to sort an array based on multiple criteria. For example, you might want to sort by lastName first and then by firstName if the lastName values are the same.

Example: Sorting by Last Name and First Name

people.sort((a, b) => {
  const lastNameComparison = a.lastName.localeCompare(b.lastName);
  if (lastNameComparison !== 0) {
    return lastNameComparison;
  }
  return a.firstName.localeCompare(b.firstName);
});

console.log(people);

In this example, the array is first sorted by lastName. If two lastName values are the same, the firstName values are compared to determine the order.

Read Convert a Set to an Array in TypeScript

Improve Performance with TypeScript

Sorting can become a performance bottleneck when dealing with large arrays. To optimize performance, consider the following tips:

  1. Avoid Unnecessary Sorting: Only sort arrays when necessary. If the data is already sorted, avoid re-sorting it.
  2. Use Efficient Sorting Algorithms: The built-in sort() method in JavaScript uses an efficient sorting algorithm, but for very large datasets, consider more specialized algorithms.
  3. Minimize DOM Manipulation: If you’re sorting data that will be displayed in the DOM, minimize the number of times you update the DOM. Batch updates can significantly improve performance.

Conclusion

In this tutorial, I explained how to sort arrays alphabetically in TypeScript with some real examples. By using the sort() method and custom comparison functions, you can sort arrays of strings and objects with ease. Whether you’re sorting city names, user directories, or product lists, the examples covered in this tutorial will help you manage and display your data effectively. Do let me know if you still have some questions.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.