How to Sort Arrays of Objects in TypeScript

Recently, I was working on a project where I needed to sort an array of customer objects by different properties like name, purchase date, and total spending. As a TypeScript developer, I’ve found that the built-in Array.sort() method is very useful, but it requires some TypeScript-specific knowledge to use correctly with complex object arrays.

In this tutorial, I will show you multiple ways to sort arrays of objects in TypeScript, from basic sorting to more advanced techniques with some real-world examples and best practices.

Basic Object Array Sorting in TypeScript

Let’s start with a simple example. Here’s an array of customer objects that I want to sort by their names:

interface Customer {
  id: number;
  name: string;
  totalSpent: number;
  joinDate: Date;
}

const customers: Customer[] = [
  { id: 1, name: "John Smith", totalSpent: 1200, joinDate: new Date("2022-01-15") },
  { id: 2, name: "Alice Johnson", totalSpent: 3500, joinDate: new Date("2021-11-03") },
  { id: 3, name: "Bob Williams", totalSpent: 850, joinDate: new Date("2023-02-27") }
];

To sort this array by customer name in alphabetical order, here’s what we do:

// Sort customers by name (A to Z)
const sortedByName = [...customers].sort((a, b) => 
  a.name.localeCompare(b.name)
);

console.log(sortedByName);

Notice I created a copy of the array with the spread operator ([...customers]) before sorting. This is because sort() modifies the original array, and it’s generally a good practice to avoid mutating your original data.

You can see the exact output in the screenshot below after I executed the TypeScript code using VS Code.

typescript sort array of objects

For string comparisons, I recommend using localeCompare() instead of the < or > operators since it handles special characters and different languages correctly.

Check out Compare Dates in TypeScript

Sort an Array of Objects by Property

When developing applications, we often need to sort an array of objects by a specific property value. This is one of the most common sorting operations in TypeScript. Here’s how to do it cleanly:

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

const products: Product[] = [
  { id: 101, name: "Wireless Headphones", price: 129.99, category: "Electronics" },
  { id: 102, name: "Running Shoes", price: 89.95, category: "Footwear" },
  { id: 103, name: "Coffee Maker", price: 59.99, category: "Kitchen" },
  { id: 104, name: "Yoga Mat", price: 24.95, category: "Fitness" }
];

// Simple function to sort by any property
function sortByProperty<T>(array: T[], property: keyof T): T[] {
  return [...array].sort((a, b) => {
    if (a[property] < b[property]) return -1;
    if (a[property] > b[property]) return 1;
    return 0;
  });
}

// Sort products by price (lowest to highest)
const sortedByPrice = sortByProperty(products, 'price');
console.log(sortedByPrice);

// Sort products by category (alphabetically)
const sortedByCategory = sortByProperty(products, 'category');
console.log(sortedByCategory);

The sortByProperty function is really versatile because:

  1. It uses TypeScript generics (<T>) to work with any type of object array
  2. The keyof T ensures you can only pass valid property names that exist on your objects
  3. It returns a new sorted array without modifying the original
  4. It works with different data types (strings, numbers, etc.)

You can see the exact output in the screenshot below:

typescript sort array of objects by property

For more complex comparisons, you can easily extend this pattern. For example, if you want to sort in descending order, just reverse the comparison:

function sortByPropertyDesc<T>(array: T[], property: keyof T): T[] {
  return [...array].sort((a, b) => {
    if (a[property] > b[property]) return -1;
    if (a[property] < b[property]) return 1;
    return 0;
  });
}

// Sort products by price (highest to lowest)
const expensiveFirst = sortByPropertyDesc(products, 'price');
console.log(expensiveFirst);

Check out Add Property to Object in TypeScript

Sort by Numeric Properties

When sorting by numeric properties like totalSpent, the approach is slightly different.

Here is the code you can use in TypeScript.

interface Customer {
  id: number;
  name: string;
  totalSpent: number;
  joinDate: Date;
}

const customers: Customer[] = [
  { id: 1, name: "John Smith", totalSpent: 1200, joinDate: new Date("2022-01-15") },
  { id: 2, name: "Alice Johnson", totalSpent: 3500, joinDate: new Date("2021-11-03") },
  { id: 3, name: "Bob Williams", totalSpent: 850, joinDate: new Date("2023-02-27") }
];
// Sort customers by total spent (highest to lowest)
const sortedBySpending = [...customers].sort((a, b) => 
  b.totalSpent - a.totalSpent
);

console.log(sortedBySpending);

Notice that I used b - a instead of a - b to sort in descending order (highest to lowest). For ascending order, you would use a - b.

You can see the exact output in the screenshot below:

typescript sort object array by property

Read Array.find() in TypeScript

Sort by Dates

Sorting by dates in TypeScript is similar to sorting numbers:

interface Customer {
  id: number;
  name: string;
  totalSpent: number;
  joinDate: Date;
}

const customers: Customer[] = [
  { id: 1, name: "John Smith", totalSpent: 1200, joinDate: new Date("2022-01-15") },
  { id: 2, name: "Alice Johnson", totalSpent: 3500, joinDate: new Date("2021-11-03") },
  { id: 3, name: "Bob Williams", totalSpent: 850, joinDate: new Date("2023-02-27") }
];

// Sort customers by join date (newest to oldest)
const sortedByJoinDate = [...customers].sort((a, b) => 
  b.joinDate.getTime() - a.joinDate.getTime()
);

console.log(sortedByJoinDate);

I convert the dates to timestamps using getTime() before comparing them. This ensures accurate date comparison.

Here is the exact output in the screenshot below:

ts sort array of objects

Check out Get Distinct Values from an Array in TypeScript

Create a Reusable Sorting Function in TypeScript

When working on larger projects, I find it helpful to create a reusable sorting function:

// Generic sorting function
function sortArray<T>(
  array: T[],
  property: keyof T,
  direction: 'asc' | 'desc' = 'asc'
): T[] {
  return [...array].sort((a, b) => {
    const valueA = a[property];
    const valueB = b[property];

    if (typeof valueA === 'string' && typeof valueB === 'string') {
      return direction === 'asc' 
        ? valueA.localeCompare(valueB) 
        : valueB.localeCompare(valueA);
    }

    if (valueA instanceof Date && valueB instanceof Date) {
      return direction === 'asc' 
        ? valueA.getTime() - valueB.getTime()
        : valueB.getTime() - valueA.getTime();
    }

    // For numbers and other comparable types
    if (valueA < valueB) return direction === 'asc' ? -1 : 1;
    if (valueA > valueB) return direction === 'asc' ? 1 : -1;
    return 0;
  });
}

// Usage examples
const nameAsc = sortArray(customers, 'name', 'asc');
const spendingDesc = sortArray(customers, 'totalSpent', 'desc');
const newCustomersFirst = sortArray(customers, 'joinDate', 'desc');

This function is type-safe with generics and handles different property types appropriately.

Check out Filter An Array with Multiple Conditions in TypeScript

Typescript: Sort Array of Objects by Multiple Properties

Sometimes, you need to sort by multiple properties. For example, sorting by state and then by city:

interface Address {
  id: number;
  state: string;
  city: string;
  zipCode: string;
}

const addresses: Address[] = [
  { id: 1, state: "California", city: "Los Angeles", zipCode: "90001" },
  { id: 2, state: "New York", city: "Buffalo", zipCode: "14201" },
  { id: 3, state: "California", city: "San Francisco", zipCode: "94016" },
  { id: 4, state: "New York", city: "New York City", zipCode: "10001" }
];

// Sort by state, then by city
const sortedAddresses = [...addresses].sort((a, b) => {
  // First compare by state
  const stateComparison = a.state.localeCompare(b.state);

  // If states are the same, compare by city
  if (stateComparison === 0) {
    return a.city.localeCompare(b.city);
  }

  return stateComparison;
});

console.log(sortedAddresses);

Case-Insensitive Sorting

For case-insensitive sorting of strings, modify your comparison like this:

const caseInsensitiveSort = [...customers].sort((a, b) => 
  a.name.toLowerCase().localeCompare(b.name.toLowerCase())
);

Sorting with Nullish Values

When dealing with properties that might be null or undefined, you need to handle those cases:

interface Product {
  id: number;
  name: string;
  discountPercentage?: number; // Optional property
}

const products: Product[] = [
  { id: 1, name: "Laptop", discountPercentage: 15 },
  { id: 2, name: "Keyboard", discountPercentage: undefined },
  { id: 3, name: "Mouse", discountPercentage: 5 },
  { id: 4, name: "Monitor", discountPercentage: null as any }
];

// Sort by discount (nullish values last)
const sortedProducts = [...products].sort((a, b) => {
  // If both are nullish, consider them equal
  if (a.discountPercentage == null && b.discountPercentage == null) return 0;

  // If only a is nullish, put it after b
  if (a.discountPercentage == null) return 1;

  // If only b is nullish, put it after a
  if (b.discountPercentage == null) return -1;

  // Normal numeric comparison
  return a.discountPercentage - b.discountPercentage;
});

console.log(sortedProducts);

Check out Filter Duplicates from an Array in TypeScript

Performance Optimization for Large TypeScript Array of Objects

When sorting large arrays (thousands of objects), performance can become an issue. Here are some optimizations I’ve used:

  1. Memoization: Cache the results of expensive comparison operations.
  2. Pre-processing: Extract and format the sorting keys before sorting.
  3. Use a more efficient sorting algorithm for special cases.

Here’s an example of pre-processing for better performance:

// Pre-process for faster sorting of a large array
function sortLargeArray<T>(array: T[], getKey: (item: T) => any): T[] {
  // Create array of [index, key] pairs
  const indexKeyPairs = array.map((item, index) => [index, getKey(item)]);
  
  // Sort the smaller pairs array
  indexKeyPairs.sort((a, b) => {
    if (a[1] < b[1]) return -1;
    if (a[1] > b[1]) return 1;
    return 0;
  });
  
  // Reconstruct the original objects in sorted order
  return indexKeyPairs.map(pair => array[pair[0] as number]);
}

// Example usage for a large array of customers
const largeCustomerArray = Array(10000).fill(null).map((_, idx) => ({
  id: idx,
  name: `Customer ${Math.random().toString(36).substring(7)}`,
  totalSpent: Math.random() * 10000,
  joinDate: new Date(Date.now() - Math.random() * 10000000000)
}));

console.time('Standard sort');
const standardSort = [...largeCustomerArray].sort((a, b) => a.totalSpent - b.totalSpent);
console.timeEnd('Standard sort');

console.time('Optimized sort');
const optimizedSort = sortLargeArray(largeCustomerArray, item => item.totalSpent);
console.timeEnd('Optimized sort');

Using External Libraries

For complex sorting needs, I would recommend considering using libraries like Lodash:

import _ from 'lodash';

// Sort by multiple properties with Lodash
const sortedWithLodash = _.orderBy(
  customers, 
  ['state', 'city'], 
  ['asc', 'desc']
);

In this tutorial, I have explained how to sort an array of objects in TypeScript using various methods. We focused more on how to sort an array of objects by property with some real examples.

Remember to consider performance for large arrays, handle nullish values appropriately, and use case-insensitive sorting when needed.

If you have any questions or would like to share other sorting techniques, I’d love to hear about them in the comments section below.

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App