How to Sort String Arrays in TypeScript?

As a developer, I received a requirement to sort arrays in TypeScript. There are different methods to sort string arrays in TypeScript, such as using the built-in sort() method, custom sorting functions, and other approaches. In this tutorial, I will explain how to sort string arrays in TypeScript with some examples.

Using the Built-in sort() Method

TypeScript arrays have a built-in sort() method that allows you to sort elements in place. By default, the sort() method sorts elements in ascending order based on their UTF-16 code unit values. Here’s an example:

const names = ["John", "Alice", "Bob", "Emma", "David"];
names.sort();
console.log(names); // Output: ["Alice", "Bob", "David", "Emma", "John"]

In this example, we have an array of strings containing common American names. By calling the sort() method on the names array, the strings are sorted in ascending order based on their UTF-16 code unit values.

Here is the exact output in the screenshot below:

Sort String Arrays in TypeScript

Check out Convert an Array to a String in TypeScript

Custom Sorting Functions

While the default sorting behavior of the sort() method works well for many cases, sometimes you may need more control over the sorting order. TypeScript allows you to provide a custom sorting function to the sort() method. Here’s an example:

const names = ["John", "Alice", "Bob", "Emma", "David"];
names.sort((a, b) => a.localeCompare(b));
console.log(names); // Output: ["Alice", "Bob", "David", "Emma", "John"]

In this example, we pass a custom sorting function to the sort() method. The function takes two parameters, a and b, which represent two elements being compared. We use the localeCompare() method to compare the strings based on their locale-specific ordering.

Sorting in Descending Order

By default, the sort() method sorts elements in ascending order. However, you can easily sort strings in descending order by modifying the custom sorting function. Here’s an example:

const names = ["John", "Alice", "Bob", "Emma", "David"];
names.sort((a, b) => b.localeCompare(a));
console.log(names); // Output: ["John", "Emma", "David", "Bob", "Alice"]

In this example, we swap the order of a and b in the localeCompare() method call. By comparing b to a instead of a to b, the strings are sorted in descending order.

Here is the exact output in the screenshot below:

How to Sort String Arrays in TypeScript

Check out Convert an Object to an Array in TypeScript

Sorting Case-Insensitive Strings

By default, the sort() method is case-sensitive, meaning uppercase letters come before lowercase letters. If you want to perform a case-insensitive sort, you can modify the custom sorting function. Here’s an example:

const names = ["John", "alice", "Bob", "emma", "David"];
names.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));
console.log(names); // Output: ["alice", "Bob", "David", "emma", "John"]

In this example, we pass an additional options object to the localeCompare() method. By setting the sensitivity option to 'base', the comparison becomes case-insensitive.

Sorting Arrays with Mixed Types

When sorting arrays that contain elements of different types, TypeScript uses type coercion to compare the elements. This can lead to unexpected results. To ensure consistent sorting behavior, it’s recommended to use a custom sorting function that explicitly handles the comparison based on the expected types. Here’s an example:

const mixedArray = [1, "10", "2", 5, "John", "Alice"];
mixedArray.sort((a, b) => {
  if (typeof a === 'number' && typeof b === 'number') {
    return a - b;
  }
  return String(a).localeCompare(String(b));
});
console.log(mixedArray); // Output: [1, "2", 5, "10", "Alice", "John"]

In this example, we have an array mixedArray that contains both numbers and strings. The custom sorting function checks the types of the elements being compared.

If both elements are numbers, it performs a numeric comparison using subtraction. Otherwise, it converts the elements to strings and uses the localeCompare() method for string comparison.

Check out Convert a Set to an Array in TypeScript

Sorting Arrays of Objects

When working with arrays of objects, you often need to sort based on specific object properties. TypeScript allows you to access object properties within the custom sorting function. Here’s an example:

interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: "John", age: 30 },
  { name: "Alice", age: 25 },
  { name: "Bob", age: 35 },
  { name: "Emma", age: 28 },
];

people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people);
/*
Output:
[
  { name: "Alice", age: 25 },
  { name: "Bob", age: 35 },
  { name: "Emma", age: 28 },
  { name: "John", age: 30 }
]
*/

In this example, we have an array people that contains objects representing persons with name and age properties. We define a custom sorting function that compares the name property of each object using the localeCompare() method. The array is sorted based on the names in ascending order.

Conclusion

In this tutorial, I explained how to sort string arrays in Typescript using different methods. The built-in sort() method provides a convenient way to sort strings in ascending order by default. However, you can also use custom sorting functions to control the sorting order, perform case-insensitive sorting, handle arrays with mixed types, and sort arrays of objects based on specific properties.

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.