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

In this tutorial, I will explain how to sort an array of objects by a specific property value in TypeScript. TypeScript provides built-in methods to accomplish this effectively. We’ll explore different approaches and examples to sort arrays of objects based on various criteria.

First you should have an understanding of Array.sort() method in TypeScript.

Understanding the Array.sort() Method

In TypeScript, you can use the Array.prototype.sort() method to sort an array of objects by a property value. This method accepts an optional compare function that defines the sort order. By default, the sort() method sorts the elements as strings in alphabetical and ascending order.

Here’s a basic example of sorting an array of objects by a property:

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

const people: Person[] = [
  { name: 'John Smith', age: 30 },
  { name: 'Emily Davis', age: 25 },
  { name: 'Michael Johnson', age: 35 },
];

people.sort((a, b) => a.age - b.age);

console.log(people);

In this example, we define an interface Person with name and age properties. We create an array of Person objects and use the sort() method with a compare function that compares the age property of two objects. The array is sorted based on the age in ascending order.

Here is the exact output in the screenshot below:

Sort an Array of Objects by Property Value in TypeScript

Check out How to Sort Arrays in TypeScript?

Sort an Array of Objects by String Property in TypeScript

When sorting objects by a string property, you can use the localeCompare() method for case-insensitive comparison. Here’s an example:

interface User {
  firstName: string;
  lastName: string;
  email: string;
}

const users: User[] = [
  { firstName: 'Alice', lastName: 'Johnson', email: 'alice@example.com' },
  { firstName: 'Bob', lastName: 'Smith', email: 'bob@example.com' },
  { firstName: 'Charlie', lastName: 'Brown', email: 'charlie@example.com' },
];

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

console.log(users);

In this example, we have an array of User objects with firstName, lastName, and email properties. We sort the array based on the lastName property using the localeCompare() method, which performs a case-insensitive comparison.

Here is the exact output in the screenshot below:

Sort an Array of Objects by String Property in TypeScript

Check out How to Filter an Array of Objects in TypeScript?

Sort an Array of Objects by Multiple Properties in TypeScript

Sometimes, you may need to sort objects based on multiple properties in TypeScript. You can achieve this by chaining multiple comparisons in the compare function. Here’s an example:

interface Student {
  name: string;
  grade: number;
  age: number;
}

const students: Student[] = [
  { name: 'Sarah Thompson', grade: 10, age: 16 },
  { name: 'David Wilson', grade: 12, age: 18 },
  { name: 'Emily Harris', grade: 10, age: 17 },
  { name: 'Michael Taylor', grade: 11, age: 16 },
];

students.sort((a, b) => {
  if (a.grade !== b.grade) {
    return b.grade - a.grade; // Sort by grade in descending order
  }
  return a.age - b.age; // If grades are equal, sort by age in ascending order
});

console.log(students);

In this example, we have an array of Student objects with name, grade, and age properties. We sort the array based on the grade property in descending order. If two students have the same grade, we sort them by age in ascending order.

Read How to Filter Arrays in TypeScript?

Using External Libraries for Sorting

In addition to the built-in sort() method, you can also leverage external libraries like Lodash to simplify sorting operations. Lodash provides the _.sortBy() function that allows you to easily sort an array of objects by one or more properties.

Here’s an example using Lodash:

import _ from 'lodash';

interface Product {
  name: string;
  price: number;
  category: string;
}

const products: Product[] = [
  { name: 'iPhone', price: 999, category: 'Electronics' },
  { name: 'T-Shirt', price: 19.99, category: 'Clothing' },
  { name: 'Laptop', price: 1499, category: 'Electronics' },
  { name: 'Sneakers', price: 79.99, category: 'Footwear' },
];

const sortedProducts = _.sortBy(products, ['category', 'price']);

console.log(sortedProducts);

In this example, we have an array of Product objects with name, price, and category properties. We use Lodash’s _.sortBy() function to sort the array based on the category and price properties. The array is first sorted by category in ascending order, and then by price within each category.

Performance Considerations

When sorting large arrays of objects, performance can be a concern. The built-in sort() method has a time complexity of O(n log n) on average and O(n^2) in the worst case. If you are dealing with massive datasets, you may need to consider alternative sorting algorithms or optimize your code.

Here are a few tips to improve sorting performance:

  • Use a custom compare function that minimizes the number of comparisons.
  • Consider using a more efficient sorting algorithm like QuickSort or MergeSort for large datasets.
  • If you need to sort the same array multiple times, consider caching the sorted result to avoid redundant sorting operations.

Conclusion

By using the built-in sort() method in TypeScript and providing a custom compare function, you can easily sort objects based on specific properties. You can sort objects by a single property, multiple properties, or even use external libraries like Lodash for more advanced sorting capabilities.

I hope this tutorial has provided you with a detailed understanding of how to sort arrays of objects by Property Value in TypeScript.

You may also like: