How to Sort an Array Alphabetically
A quick recipe for sorting an array of strings or an array of objects by a string field in TypeScript.
Sorting arrays alphabetically is a common task. TypeScript uses the sort()
method on arrays, but it can be a bit tricky because it sorts in place and, by
default, converts elements to strings for comparison.
Here’s how I handle sorting for both simple string arrays and arrays of objects.
Sorting an Array of Strings
For a simple array of strings, you can use sort()
with localeCompare()
to
ensure correct alphabetical sorting across different languages and locales.
I always use toSorted()
instead of sort()
because it returns a new sorted
array, leaving the original array unchanged. This avoids unexpected side
effects.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const sortedFruits = fruits.toSorted((a, b) => a.localeCompare(b));
console.log(sortedFruits);
// Output: ["Apple", "Banana", "Mango", "Orange"]
Sorting an Array of Objects
When sorting an array of objects by a string property, the approach is similar.
You provide a custom comparison function to toSorted()
that accesses the
property and uses localeCompare()
.
Here’s how I sort an array of users by their name
.
type User = {
id: number;
name: string;
};
const users: User[] = [
{ id: 1, name: "John" },
{ id: 2, name: "Alice" },
{ id: 3, name: "Bob" }
];
const sortedUsers = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(sortedUsers);
// Output:
// [
// { id: 2, name: 'Alice' },
// { id: 3, name: 'Bob' },
// { id: 1, name: 'John' }
// ]
Using toSorted()
with localeCompare()
is my standard way to handle
alphabetical sorting. It’s predictable and prevents bugs that can come from
modifying arrays directly.