Hello Friends 👋,

Welcome To Infinitbility! ❤️

TypeScript almost has the same syntax to do sorting of objects of array-like javascript i.e .sort() but in this tutorial, we will learn to do sorting of array-based on objects and how to use .sort() in typescript.

Here, we will learn to

  1. defined object structure using the interface
  2. use interface to create an array of objects
  3. use sort with static typing to sort an array

Let’s start today’s tutorial How to sort an array of objects by a property value in typescript?

Before creating an array of objects, we have to define the structure of objects it’s standard of typescript.

Here, the structure of our object ( interface ) which we are going to use to create an array of objects.

interface user {
  id: number,
  name: string,
};

Now, time to create an array of objects using our interface user.

let users: Array<user> = [
  { id: 1, name: 'infinit' },
  { id: 2, name: 'bility' },
  { id: 3, name: 'infinitbility' },
];

After creating, an array of objects users it’s time to sort array using name property value.

users.sort((a: user, b: user) => (a.name > b.name) ? 1 : -1);

it will sort an array of objects users by their name property value alphabetical wise…

Here, complete code example with output.

users.ts

interface user {
  id: number,
  name: string,
};

let users: Array<user> = [
  { id: 1, name: 'infinit' },
  { id: 2, name: 'bility' },
  { id: 3, name: 'infinitbility' },
];

users.sort((a: user, b: user) => (a.name > b.name) ? 1 : -1);

Output

Array of objects, sorting, typescript, Example

Thanks for reading…