How to use Intl.Collator for Sorting In Typescript
The approach involves creating an instance of Intl.Collator with numeric sorting enabled. Then, the array of objects is sorted based on a specific property using the collator’s compare method, ensuring correct sorting, especially with non-ASCII characters.
Example: In this example we define a Person interface with name and age properties. Sort an array of Person objects by age in ascending order using simple numeric comparison, then print the sorted array.
interface Person {
name: string;
age: number;
}
const arrayOfObjects: Person[] = [
{ name: "XYZ", age: 25 },
{ name: "MNO", age: 35 },
{ name: "ABC", age: 30 }
];
// Use the default collator to sort numbers
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base'
});
// Use a simple comparison of numbers
arrayOfObjects.sort((a, b) => a.age - b.age);
console.log(arrayOfObjects);
Output:
[
{ name: 'XYZ', age: 25 },
{ name: 'ABC', age: 30 },
{ name: 'MNO', age: 35 }
]
How to Sort an Array of Object using a Value in TypeScript ?
Sorting an array of objects using a value in TypeScript pertains to the process of arranging an array of objects in a specified order based on a particular property or value contained within each object.
The below approaches can be used to sort an array of objects using a value in TypeScript:
Table of Content
- Using the Array.prototype.sort()
- Using the Lodash library
- Using Intl.Collator for Sorting
Contact Us