When I work with API responses, sales dashboards, or customer lists, I often need to arrange data before displaying it. A TypeScript application may receive orders in a random order, product prices without ranking, or customer names that need alphabetical sorting.
TypeScript is JavaScript with static type checking, while an array is an ordered collection of values. TypeScript uses JavaScript’s built-in array methods, but its type system helps you write safer sorting logic.
In this guide, you will learn how to sort arrays in TypeScript, including numbers, strings, objects, and dates, while understanding mutation and type safety.
How to Sort Arrays in TypeScript with sort()
The simplest way to sort an array in TypeScript is with the sort() method.
One important detail is that sort() changes the original array. This behavior is called mutation, which means directly changing an existing value or object.
Sort a string array alphabetically
Suppose a sales dashboard stores customer names.
const customers: string[] = [
"Michael",
"Sarah",
"David",
"Jennifer"
];
customers.sort();
console.log(customers);Output:
[ 'David', 'Jennifer', 'Michael', 'Sarah' ]You can see the output in the screenshot below.

The sort() method arranges strings alphabetically by default. Because it mutates the array, the customers variable now contains the sorted values.
If you are learning more about strongly typed collections, see how to find the length of an array in TypeScript.
How to Sort Numbers in TypeScript
Sorting numbers requires extra care.
The default sort() behavior converts values to strings before comparing them. That can produce unexpected results.
Incorrect numeric sorting
const prices: number[] = [100, 25, 5, 300];
prices.sort();
console.log(prices);Output:
[ 100, 25, 300, 5 ]You can see the output in the screenshot below.

This happens because JavaScript compares the string versions of the values.
Sort numbers in ascending order
Use a comparison function to sort numbers correctly.
A function is a reusable block of code that performs a task. The comparison function receives two values and tells sort() which one should appear first.
const prices: number[] = [100, 25, 5, 300];
prices.sort((a, b) => a - b);
console.log(prices);Output:
[ 5, 25, 100, 300 ]You can see the output in the screenshot below.

The expression a - b works as follows:
- A negative result places
abeforeb. - A positive result places
bbeforea. - Zero keeps both values at the same sorting priority.
This approach works well for prices, quantities, scores, and other numeric data.
How to Sort Arrays in TypeScript in Descending Order
To sort numbers from highest to lowest, reverse the comparison.
const sales: number[] = [4500, 1200, 8900, 3200];
sales.sort((a, b) => b - a);
console.log(sales);Output:
[ 8900, 4500, 3200, 1200 ]Here, b - a tells TypeScript to place larger values first.
This pattern is useful when displaying:
- Highest sales first
- Top-performing employees
- Most expensive products
- Latest rankings
For more TypeScript array techniques, you can also read how to get the first element of an array in TypeScript.
Sort Strings with localeCompare()
For more controlled alphabetical sorting, use localeCompare().
This method compares two strings and returns a value that indicates their alphabetical relationship.
const cities: string[] = [
"Seattle",
"Austin",
"Boston",
"Chicago"
];
cities.sort((a, b) => a.localeCompare(b));
console.log(cities);Output:
[ 'Austin', 'Boston', 'Chicago', 'Seattle' ]This approach makes your comparison logic explicit and works well when sorting customer names, product names, and locations.
Sort strings in descending order
const cities: string[] = [
"Seattle",
"Austin",
"Boston",
"Chicago"
];
cities.sort((a, b) => b.localeCompare(a));
console.log(cities);Output:
[ 'Seattle', 'Chicago', 'Boston', 'Austin' ]Sort an Array of Objects in TypeScript
Real applications often work with object arrays instead of simple strings or numbers.
An interface defines the expected structure of an object. It helps TypeScript provide type safety, which catches incorrect data usage during development.
Suppose an order-processing service stores sales orders.
interface Order {
id: number;
customer: string;
total: number;
}
const orders: Order[] = [
{ id: 101, customer: "John Miller", total: 450 },
{ id: 102, customer: "Emily Davis", total: 125 },
{ id: 103, customer: "Robert Wilson", total: 780 }
];
orders.sort((a, b) => a.total - b.total);
console.log(orders);Output:
[
{ id: 102, customer: 'Emily Davis', total: 125 },
{ id: 101, customer: 'John Miller', total: 450 },
{ id: 103, customer: 'Robert Wilson', total: 780 }
]The comparison function accesses the total property from each object and sorts the orders from lowest to highest.
For a detailed object sorting example, see how to sort an array of objects by property value in TypeScript.
Sort objects by a string property
You can also sort objects alphabetically.
interface Employee {
id: number;
name: string;
department: string;
}
const employees: Employee[] = [
{ id: 1, name: "Sarah Johnson", department: "Sales" },
{ id: 2, name: "David Brown", department: "Engineering" },
{ id: 3, name: "Amanda Taylor", department: "Marketing" }
];
employees.sort((a, b) => a.name.localeCompare(b.name));
console.log(employees);Output:
[
{ id: 3, name: 'Amanda Taylor', department: 'Marketing' },
{ id: 2, name: 'David Brown', department: 'Engineering' },
{ id: 1, name: 'Sarah Johnson', department: 'Sales' }
]Sort an Array by Date in TypeScript
Date sorting is common when working with orders, support tickets, activity logs, and API responses.
The safest approach is to convert each date into a numeric timestamp before comparing them.
interface SupportTicket {
id: number;
title: string;
createdDate: string;
}
const tickets: SupportTicket[] = [
{
id: 1,
title: "Login issue",
createdDate: "2026-08-28"
},
{
id: 2,
title: "Payment error",
createdDate: "2026-08-31"
},
{
id: 3,
title: "Profile update problem",
createdDate: "2026-08-25"
}
];
tickets.sort(
(a, b) =>
new Date(a.createdDate).getTime() -
new Date(b.createdDate).getTime()
);
console.log(tickets);Output:
[
{
id: 3,
title: 'Profile update problem',
createdDate: '2026-08-25'
},
{
id: 1,
title: 'Login issue',
createdDate: '2026-08-28'
},
{
id: 2,
title: 'Payment error',
createdDate: '2026-08-31'
}
]This code converts both dates into timestamps and compares the numeric values.
For more examples, see how to sort an array by date in TypeScript and how to sort arrays by date in TypeScript.
Sort an Array Without Changing the Original
Because sort() mutates an array, it can cause problems when multiple parts of an application use the same array.
For example, a frontend component may expect the original API order while another component needs a sorted version.
You can create an array copy with spread syntax before sorting.
const originalScores: number[] = [85, 40, 95, 60];
const sortedScores = [...originalScores].sort((a, b) => a - b);
console.log("Original:", originalScores);
console.log("Sorted:", sortedScores);Output:
Original: [ 85, 40, 95, 60 ]
Sorted: [ 40, 60, 85, 95 ]The spread syntax creates a new array. The sort() method then changes only that new array.
You can learn more about this syntax in the TypeScript spread operator guide.
Pro Tip: I have seen subtle bugs when a shared API result gets sorted directly. I usually create a copy first unless I intentionally want every reference to use the new order.
Use toSorted() for a Non-Mutating Sort
Modern JavaScript provides toSorted(), which returns a new sorted array instead of changing the original.
const inventory: number[] = [50, 10, 75, 25];
const sortedInventory = inventory.toSorted((a, b) => a - b);
console.log("Original:", inventory);
console.log("Sorted:", sortedInventory);Output:
Original: [ 50, 10, 75, 25 ]
Sorted: [ 10, 25, 50, 75 ]This method clearly communicates your intention: create a sorted result without mutation.
Make sure your JavaScript runtime and TypeScript configuration support toSorted() before using it in production. If you need wider compatibility, [...array].sort() remains a practical option.
Sort a Readonly Array in TypeScript
A readonly array is an array that TypeScript prevents you from modifying directly.
You cannot call a mutating operation such as sort() on a readonly array.
const productIds: readonly number[] = [40, 10, 30, 20];
const sortedProductIds = [...productIds].sort((a, b) => a - b);
console.log(sortedProductIds);
console.log(productIds);Output:
[ 10, 20, 30, 40 ]
[ 40, 10, 30, 20 ]The spread operator creates a regular mutable copy, allowing you to sort the copied values.
For more details, read readonly arrays in TypeScript.
Create a Generic Sorting Function in TypeScript
A generic function is a reusable function that works with different data types while preserving type information.
You can create a reusable helper for sorting any array.
function sortArray<T>(
items: readonly T[],
compareFn: (a: T, b: T) => number
): T[] {
return [...items].sort(compareFn);
}
const numbers: number[] = [30, 10, 20];
const names: string[] = ["Michael", "Amanda", "David"];
const sortedNumbers = sortArray(numbers, (a, b) => a - b);
const sortedNames = sortArray(
names,
(a, b) => a.localeCompare(b)
);
console.log(sortedNumbers);
console.log(sortedNames);Output:
[ 10, 20, 30 ]
[ 'Amanda', 'David', 'Michael' ]The <T> type parameter allows the function to work with numbers, strings, objects, or other typed values.
The readonly T[] parameter also protects the original input from modification.
Sort an Array Manually with a Loop
Most applications should use the built-in sort() method because it is simpler and optimized by the JavaScript engine.
However, manually sorting values can help you understand how sorting algorithms work.
The following example uses a simple bubble-sort approach.
const values: number[] = [30, 10, 50, 20];
for (let i = 0; i < values.length - 1; i++) {
for (let j = 0; j < values.length - 1 - i; j++) {
if (values[j] > values[j + 1]) {
const temporaryValue = values[j];
values[j] = values[j + 1];
values[j + 1] = temporaryValue;
}
}
}
console.log(values);Output:
[ 10, 20, 30, 50 ]The code repeatedly compares neighboring values and swaps them when they appear in the wrong order.
I would use this approach for learning, not for normal application code. The built-in sort() method is usually the better choice.
If you want to learn more about loops, see TypeScript forEach loop with index.
Things to Keep in Mind
- sort() mutates the original array: Create a copy with spread syntax when other parts of your application need the original order.
- Numbers need a comparison function: Use
(a, b) => a - bfor ascending numeric sorting and(a, b) => b - afor descending sorting. - Use localeCompare() for strings: It provides clear and intentional string comparison logic.
- Consider readonly arrays: Copy a readonly array before sorting because TypeScript blocks mutating methods.
- Avoid unnecessary copies for huge datasets: Copying large arrays uses additional memory, so mutate only when your application safely allows it.
- Sorting differs from reversing: Sorting calculates a new order based on comparisons, while reversing simply flips the existing order.
Frequently Asked Questions
How do I sort an array in TypeScript?
Use the sort() method. For strings, array.sort() often works directly, while numbers usually require a comparison function such as (a, b) => a - b.
Does sort() mutate an array in TypeScript?
Yes. sort() changes the original array directly. Use [...array].sort() or toSorted() when you need to preserve the original array.
How do I sort numbers in TypeScript?
Use a comparison function. For ascending order, use (a, b) => a - b, and for descending order, use (a, b) => b - a.
How do I sort an array of objects in TypeScript?
Create a comparison function that compares object properties. For example, orders.sort((a, b) => a.total - b.total) sorts orders by their numeric total property.
Can I sort a readonly array in TypeScript?
Yes, but you cannot sort it directly because sort() mutates arrays. Create a copy with [...readonlyArray] and sort the copy instead.
What is the difference between sort() and toSorted()?
sort() changes the existing array, while toSorted() returns a new sorted array and keeps the original unchanged. Choose toSorted() when your runtime supports it and immutability matters.
Sorting arrays in TypeScript becomes straightforward once you understand comparison functions and mutation. Use sort() when changing the original array is acceptable, and prefer toSorted() or [...array].sort() when you need to preserve the original data.
You May Also Like
- How to sort an array of objects by property value in TypeScript
- How to sort an array by date in TypeScript
- How to check whether an array contains a value in TypeScript
- How to get the first element of an array in TypeScript
- TypeScript best practices

Bijay Kumar is an experienced Python and AI professional who enjoys helping developers learn modern technologies through practical tutorials and examples. His expertise includes Python development, Machine Learning, Artificial Intelligence, automation, and data analysis using libraries like Pandas, NumPy, TensorFlow, Matplotlib, SciPy, and Scikit-Learn. At PythonGuides.com, he shares in-depth guides designed for both beginners and experienced developers. More about us.