How to use the Array.prototype.sort() In Typescript

This method is a built-in JavaScript function that sorts the elements of an array in place and returns the sorted array. You provide a comparison function that defines the sort order based on the values of the objects being sorted.

Example: The below example sorts an array of objects based on age property using Array.prototype.sort().

Javascript
interface Person {
    name: string;
    age: number;
}

const arrayOfObjects: Person[] = [
    { name: "ABC", age: 30 },
    { name: "XYZ", age: 25 },
    { name: "MNO", age: 35 }
];

arrayOfObjects.sort((a: Person, b: Person) => 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

Similar Reads

Using the Array.prototype.sort()

This method is a built-in JavaScript function that sorts the elements of an array in place and returns the sorted array. You provide a comparison function that defines the sort order based on the values of the objects being sorted....

Using the Lodash library

Lodash is a popular utility library that provides many helpful functions for manipulating arrays, objects, and other data structures. The _.sortBy() function sorts the elements of an array based on the specified property of each object in ascending order....

Using Intl.Collator for Sorting

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....