How to Sort an Array of Objects by Property in TypeScript?

In this tutorial, I will explain how to sort an array of objects by a property in TypeScript. This is a very common requirement for TypeScript developers.

Sorting arrays is important for many applications. For example, if you are building an application that displays a list of users, you might want to sort them alphabetically by their last names or by their registration dates. Sorting helps in organizing data, making it easier to read and analyze.

Sort an Array of Objects by Property in TypeScript

Now, let me show you some examples related to sorting an array of objects by property in TypeScript.

1. Basic Sorting in TypeScript

TypeScript uses the same sort() method as JavaScript but with added type safety. Let’s start with a simple example where we sort an array of numbers:

const numbers: number[] = [5, 3, 8, 1, 2];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 3, 5, 8]

In this example, we sort the array in ascending order using a comparison function that subtracts b from a.

Here is the exact output in the screenshot below:

Python invalid literal for int() with base 10

Check out Search an Array of Objects by Property in TypeScript

2. Sorting an Array of Objects

Now, let’s move on to sorting an array of objects. Consider an array of user objects where each user has a firstName, lastName, and age:

interface User {
  firstName: string;
  lastName: string;
  age: number;
}

const users: User[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Smith', age: 25 },
  { firstName: 'Michael', lastName: 'Johnson', age: 35 },
  { firstName: 'Emily', lastName: 'Davis', age: 28 },
];

3. Sorting an Array of Objects by Last Name

To sort this array by the lastName property, we can use the sort() method with a custom comparison function:

interface User {
  firstName: string;
  lastName: string;
  age: number;
}

const users: User[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Smith', age: 25 },
  { firstName: 'Michael', lastName: 'Johnson', age: 35 },
  { firstName: 'Emily', lastName: 'Davis', age: 28 },
];
users.sort((a, b) => a.lastName.localeCompare(b.lastName));
console.log(users);

This will sort the users alphabetically by their last names. The localeCompare method is used to compare strings in a locale-sensitive manner.

You can see the exact output in the screenshot below:

Sort an Array of Objects by Property in TypeScript

Read Remove Undefined Values from an Array in TypeScript

4. Sorting an Array of Objects by Age

If you want to sort the users by age, you can modify the comparison function:

interface User {
  firstName: string;
  lastName: string;
  age: number;
}

const users: User[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Smith', age: 25 },
  { firstName: 'Michael', lastName: 'Johnson', age: 35 },
  { firstName: 'Emily', lastName: 'Davis', age: 28 },
];
users.sort((a, b) => a.age - b.age);
console.log(users);

This will sort the users in ascending order of their ages.

Check out Get Distinct Values from an Array in TypeScript

5. Sorting by Multiple Properties

Sometimes, you may need to sort by multiple properties. For example, you might want to sort users by their last names and then by their first names if their last names are the same. Here’s how you can achieve this:

interface User {
  firstName: string;
  lastName: string;
  age: number;
}

const users: User[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Smith', age: 25 },
  { firstName: 'Michael', lastName: 'Johnson', age: 35 },
  { firstName: 'Emily', lastName: 'Davis', age: 28 },
];
users.sort((a, b) => {
  const lastNameComparison = a.lastName.localeCompare(b.lastName);
  if (lastNameComparison !== 0) {
    return lastNameComparison;
  }
  return a.firstName.localeCompare(b.firstName);
});
console.log(users);

In this example, we first compare the lastName properties. If they are not equal, we return the result of that comparison. If they are equal, we then compare the firstName properties.

Read Convert an Object to an Array in TypeScript

6. Sorting in Descending Order

To sort in descending order, you can simply reverse the comparison:

interface User {
  firstName: string;
  lastName: string;
  age: number;
}

const users: User[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Smith', age: 25 },
  { firstName: 'Michael', lastName: 'Johnson', age: 35 },
  { firstName: 'Emily', lastName: 'Davis', age: 28 },
];
users.sort((a, b) => b.age - a.age);
console.log(users);

This will sort the users by age in descending order.

You can see the exact output in the screenshot below:

How to Sort an Array of Objects by Property in TypeScript

7. Handling Null or Undefined Values

When sorting arrays, you might encounter null or undefined values. It’s essential to handle these cases to avoid runtime errors. Here’s an example of sorting an array that may contain null or undefined values:

interface User {
  firstName: string;
  lastName: string;
  age: number;
}

const users: User[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  { firstName: 'Jane', lastName: 'Smith', age: 25 },
  { firstName: 'Michael', lastName: 'Johnson', age: 35 },
  { firstName: 'Emily', lastName: 'Davis', age: 28 },
];
const usersWithNulls: (User | null)[] = [
  { firstName: 'John', lastName: 'Doe', age: 30 },
  null,
  { firstName: 'Jane', lastName: 'Smith', age: 25 },
  undefined,
  { firstName: 'Michael', lastName: 'Johnson', age: 35 },
];

usersWithNulls.sort((a, b) => {
  if (!a || !b) return 0;
  return a.age - b.age;
});
console.log(usersWithNulls);

In this example, we check if either a or b is null or undefined before attempting to compare their properties.

Performance Considerations

Sorting can be computationally expensive, especially for large arrays. TypeScript’s sort() method uses the efficient Timsort algorithm, but it’s still essential to consider performance. If you need to sort large datasets frequently, consider optimizing your code or using more advanced data structures.

Conclusion

Sorting arrays of objects by property in TypeScript is a powerful feature that can help you manage and organize data effectively.

In this tutorial, we covered:

  • Basic sorting with sort()
  • Sorting arrays of objects by different properties
  • Sorting by multiple properties
  • Handling null or undefined values
  • Performance considerations

Do let me know if you still have any questions.

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.