Open In App

How to Sort Objects in an Array Based on a Property in a Specific Order in TypeScript ?

Sorting objects in an array based on a specific property is a common task in software development. TypeScript, with its static typing and powerful features, provides various approaches to accomplish this task efficiently. The below approaches can be used to sort an array of objects in properties.

Using the Array.sort() Method

The Array.sort() method allows us to sort arrays based on a provided comparator function. We can define a custom comparator function that compares the desired properties of objects and sorts them accordingly.

Example: The below code uses a simple comparator function to sort an array of objects.






interface MyObject {
    id: number;
    name: string;
}
 
const objects: MyObject[] = [
    { id: 2, name: 'Object B' },
    { id: 1, name: 'Object A' },
    { id: 3, name: 'Object C' }
];
 
objects.sort((a, b) => a.id - b.id);
 
console.log(objects);

Output:

[
{ id: 1, name: 'Object A' },
{ id: 2, name: 'Object B' },
{ id: 3, name: 'Object C' }
]

Using the localeCompare() Method for Strings

When sorting objects based on string properties, such as names, we can use the localeCompare() method to perform alphabetical sorting.

Example: The below code sorts the array of objects based on the the keys that contains the string values using localeCompare() method.




interface MyObject {
    id: number;
    name: string;
}
 
const objects: MyObject[] = [
    { id: 2, name: 'Beta' },
    { id: 1, name: 'Alpha' },
    { id: 3, name: 'Gamma' }
];
 
objects.sort((a, b) => a.name.localeCompare(b.name));
console.log(objects);

Output:

[
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' },
{ id: 3, name: 'Gamma' }
]

Article Tags :