Typescript sort array [With 15 Examples]

In this typescript tutorial, we will see what is sort method in typescript and how to sort an array in typescript with the sort method. Also, we will see different examples of how we can sort arrays in typescript. Here is the example we will cover:

  • Typescript sort array
  • typescript sort array alphabetically
  • typescript sort array strings
  • typescript sort associative array
  • typescript sort array by date
  • typescript sort array by number property
  • typescript sort array by name
  • typescript sort array by two properties
  • typescript sort array based on another array
  • typescript sort array alphanumeric
  • typescript sort array by boolean property
  • typescript sort array by index
  • typescript sort array of objects by date descending
  • typescript sort array of objects by property alphabetically
  • typescript sort array of objects by property

Typescript sort array

The sort() in typescript is an inbuilt function, which is used to sort the item of an array.

Syntax of sort () in typescript

array.sort(compareFunction)

Example of sort method in typescript

We have a list of numbers, and we need to sort the array in ascending order using the sort method in typescript.

var num = [ 18, 80, 13, 70, 980 ]; 
  
// use of sort() method 
var val = num.sort();
   
// printing
console.log( val );//👉[ 13, 18, 70, 80, 980 ]

To compile the code run the below command and see the result in the console.

ts-node app.ts
Typescript sort array
typescript sort array ascending

This is an example of a typescript sort array ascending.

Typescript sort array alphabetically

Here we will see how we can sort the array of strings in alphabetical order using the sort method in typescript.

For example, we have a list of names, which we will sort in alphabetical order using the sort method in typescript.

var names = [ 'ammy', 'nancy', 'bob', 'henry', 'alex' ]; 
  
// use of sort() method 
var val = names.sort();
   
// printing
console.log( val );//👉[ 'alex', 'ammy', 'bob', 'henry', 'nancy' ]

To compile the code, run the below command and see the result in the console.

ts-node app.ts
Typescript sort array alphabetically
Typescript sort array strings

This is an example of Typescript sort array alphabetically.

Read Typescript array

Typescript sort array strings

Here we will see how we can sort an array of strings in typescript.

For example, we will create a new car array, then we will sort the array alphabetically in typescript.

In the app.ts file write the below code:

var car = new Array("Saab", "Volvo", "BMW"); 
var sorted = car.sort(); 
console.log("Returned string is : " + sorted );

To compile the code, run the below command and you can see the result in the console.

ts-node app.ts
Typescript sort array strings
Typescript sort array strings

This is an example of Typescript sort array strings.

Typescript sort associative array

Here we will see how to sort the associative arrays in typescript.

For example, if we have an array of objects, we will sort the array of objects based on the age property value. In the app.ts file, write the below code:

const emp = [
  {"id":10, "name":"John", "age":31, "gender":"m", "category":"G"},
  {"id":11, "name":"Alex", "age":35, "gender":"m", "category":"G"},
  {"id":12, "name":"Ammy", "age":20, "gender":"m", "category":"G"},
  {"id":13, "name":"Ron", "age":24, "gender":"W", "category":"M"}
];
const sorter = (a:any, b:any) => {
  return a.age - b.age;
 
};

const sortByAge = ((arr:any) => {
  arr.sort(sorter);
});

sortByAge(emp);
console.log(emp);

To compile the code, run the below command and see the result in the console.

ts-node app.ts
Typescript sort associative array
Typescript sort associative array

This is an example of a Typescript sort associative array.

Read Typescript filter array

Typescript sort array by date

Here we will see how we can sort arrays by date using the sort method in typescript.

For example, we have an array of objects, and based on the date we will sort the objects in ascending order in typescript. In the app.ts file write the below code:

const emp = [
  {"id":10, "name":"John", "age":31, "gender":"m", "category":"G",date: new Date('2022-04-21')},
  {"id":11, "name":"Alex", "age":35, "gender":"m", "category":"G",date: new Date('2022-08-23')},
  {"id":12, "name":"Ammy", "age":20, "gender":"m", "category":"G",date: new Date('2022-06-14')},
  {"id":13, "name":"Ron", "age":24, "gender":"W", "category":"M",date: new Date('2022-07-22')}
];

const sortedAsc = emp.sort(
  (objA, objB) => objA.date.getTime() - objB.date.getTime(),
  
);

console.log(sortedAsc);

To compile the code, run the below command and see the result in the console.

ts-node app.ts
Typescript sort array by date
Typescript sort array by date

This is an example of a Typescript sort array by date.

Typescript sort array of objects by date descending

Here we will see how we can sort of objects by date descending using sort method in typescript.

For example, we have an array of objects, and based on the date we will sort the objects in descending order in typescript. In the app.ts file write the below code:

const emp = [
  {"id":10, "name":"John", "age":31, "gender":"m", "category":"G",date: new Date('2022-04-21')},
  {"id":11, "name":"Alex", "age":35, "gender":"m", "category":"G",date: new Date('2022-08-23')},
  {"id":12, "name":"Ammy", "age":20, "gender":"m", "category":"G",date: new Date('2022-06-14')},
  {"id":13, "name":"Ron", "age":24, "gender":"W", "category":"M",date: new Date('2022-07-22')}
];

//--descending order----
const sortedDesc = emp.sort(
  (objA, objB) => objB.date.getTime() - objA.date.getTime(),
);
console.log(sortedDesc);

To compile the code, run the below command, you can see the result in the console.

ts-node app.ts
Typescript sort array of objects by date descending
Typescript sort array of objects by date descending

This is an example of a Typescript sort array of objects by date descending.

Read Typescript array find

Typescript sort array by number property

Here we will see how we can sort the array of objects by number property in typescript.

For example, we have a list of arrays of persons, which have names and age properties. So here we will sort the array based on age properties in descending order, which are a number type using sort() in typescript. In the app.ts file write the below code:

var person:Array<any|Number> = []
person.push({name: "Alex", age: 18})
person.push({name: "Ron", age: 50})
person.push({name: "John", age: 31});

var result = person.sort(({age:a}, {age:b}) => b-a);
console.log(result);

To compile the code run the below command and see the output in the console.

ts-node app.ts
Typescript sort array by number property
Typescript sort array by number property

This is an example of a Typescript sort array by number property.

Typescript sort array by name

Here we will see how to alphabetically sort an array of names using the sort method in typescript.

For example, we have a person array, which contains the person’s name and age, so based on the person’s name, we will sort the array in alphabetical order using the typescript sort method.

In the app.ts file write the below code to sort the array by name.

let person = [
  {
    name: "Rohn Doe",
    age: 17
  },
  {
    name: "Elon Musk",
    age: 27
  },
  {
    name: "Alex Doe",
    age: 14
  }
];
person.sort(function (N1, N2) {
  if (N1.name < N2.name) {
    return -1;
  }
  if (N1.name > N2.name) {
    return 1;
  }
  return 0;
});

console.log(person);

To compile the code, run the below command and see the result in the console.

ts-node app.ts
Typescript sort array by name
Typescript sort array by name

This is an example of a Typescript sort array by name.

Read Typescript type annotation

Typescript sort array by two properties

Here we will see how we can sort an array of objects by two properties using the sort method in typescript.

For example, we will work on a sort method to alphabetically sort an array of objects based on two columns or two properties. In the app.ts file write the below code:

var usaActors = [
  {first_name: 'Robin', last_name: 'Williams'},
  {first_name: 'Morgan', last_name: 'Freeman'},
  {first_name: 'Tom', last_name: 'Hanks'},
  {first_name: 'Bruise', last_name: 'Wilis'},
  {first_name: 'Brad', last_name: 'Pit'},
]

console.log(usaActors.sort((a, b)=> {
  if (a.first_name === b.first_name){
    return a.last_name < b.last_name ? -1 : 1
  } else {
    return a.first_name < b.last_name ? -1 : 1
  }
}))

To compile the code run the below command and see the result in the console.

ts-node app.ts
Typescript sort array by two properties
Typescript sort array by two properties

This is an example of a Typescript sort array by two properties.

Typescript sort array based on another array

Here we will see how we can sort an array based on another array using the sort method in typescript.

For example, we will sort the names array, such that the items present in the sortOrder array item will appear right at the beginning of the name array, and all other items will be in the same position.

In the app.ts file write the below code:

const names = ['Alex', 'Ammy', 'Den','John',  'Kenry','Ron', ];
const sortOrder = ['Ammy', 'Kenry'];
const sorter = (x: any, y: any) => {
   if(sortOrder.includes(x)){
      return -1;
   };
   if(sortOrder.includes(y)){
      return 1;
   };
   return 0;
};
names.sort(sorter);
console.log(names);

To compile the code, run the below command and you can see the result in the console.

ts-node app.ts
Typescript sort array based on another array
Typescript sort array based on another array

This is an example of a Typescript sort array based on another array.

Read Typescript Identifiers and Keywords

Typescript sort array alphanumeric

Here we will see how we can sort alphanumeric arrays in typescript.

For example, we have an alphanumeric string of an array, so we will see how we can sort the array using the sort method and localeCompare method in typescript.

As we already discussed what the sort method is and coming to the localeCompare method, return a number showing, if a reference string comes before or after or it is identical to the given string in sort order.

In the app.ts file write the below code:

const alphanumericArray = [
  'Typescript',
  '123Typescript',
  '12345typescript',
  'typescript123',
  'typescript12',
];
const sortedArray = alphanumericArray.sort((a, b) => {
  return a.localeCompare(b, undefined, {
    numeric: true,
    sensitivity: 'base'
  })
});
console.log(sortedArray);

To compile the code run the below command and see the result in the console.

ts-node app.ts
Typescript sort array alphanumeric
Typescript sort array alphanumeric

This is an example of a typescript sort array alphanumeric.

Typescript sort array by boolean property

Here we will see how we can sort an array by boolean property using the sort method in typescript.

For example, we will have an array of objects with boolean property, then we will convert the boolean property to a number. Next, we will subtract the first number from the second number, and we will use the sort method to sort the array of objects by the boolean property.

In the app.ts file, write the below code:

const isProjectAvailable = [{name:"Employee Management",available: true}, {name:"Leave Management",available: false}, {name:" Online Parking management",available: false}, {name:"Online course Portal",available: true}];


const trueFirst = isProjectAvailable.sort((a, b) => Number(b.available) - Number(a.available));

// 👇️ [{available: true}, {available: true}, {available: false}, {available: false}]
console.log(trueFirst);

To compile the code, run the below command, you can see the result in the console.

ts-node app.ts
Typescript sort array by boolean property
Typescript sort array by boolean property

This is an example of a Typescript sort array by boolean property

Read TypeScript Enum

Typescript sort array by index

Here we will see how we can sort an array by index using the typescript sort method.

For example, we will sort the array of objects, by using the index property in increasing order using the sort method in typescript.

const arr = [
   {
      'name' : 'd',
      'index' : 3
   },
   {
      'name' : 'c',
      'index' : 2
   },
   {
      'name' : 'a',
      'index' : 0
   },
   {
      'name' : 'b',
      'index' : 1
   }
];
const sortAndMap = (xyz : any = []) => {
   const copy = xyz.slice();
   const sorter = (a:any, b:any) => {
      return a['index'] - b['index'];
   };
   copy.sort(sorter);
   const res = copy.map((name:any, index: any) => {
      return name;
   });
   return res;
};
console.log(sortAndMap(arr)); 

To compile the code run the below command and you can see the result in the console:

ts-node app.ts
Typescript sort array by index
Typescript sort array by index

This is an example of a Typescript sort array by index.

Typescript sort array of objects by property alphabetically

Here we will see how we can sort an array of objects by property alphabetical order using the sort method.

For example, we have an array of objects, in which we will sort the names alphabetically order using the sort method.

console.log("Sort Array of Objects Alphabetically");
const player_names = [
    { name: 'Henry' },
    { name: 'Alex' },
    { name: 'Mike' },
    { name: 'Bale' },
];
let sort_names = player_names.sort(function (a, b) {
   if (a.name < b.name) {
     return -1;
   }
   if (a.name > b.name) {
     return 1;
   }
   return 0;
 });
 
console.log(sort_names);

To compile the code, run the below command and you can see the result in the console.

ts-node app.ts
Typescript sort array of objects by property alphabetically
Typescript sort array of objects by property alphabetically

This is an example of typescript sort array of objects by property alphabetically.

Typescript sort array of objects by property

Here we will see how we can sort array of objects by property using sort method in typescript.

For example, we will use the sort method to sort the array of objects by name property. In the app.ts file write the below code:

const users = [  
   { id: 21, name: 'Marry' },
   { id: 11, name: 'Celia' },
   { id: 33, name: 'Nancy' }
 ]

 let sort=users.sort((a, b) => {  
   return a.name >= b.name
     ? 1
     : -1
 })

 console.log(sort);

To compile the code, run the below command and you can see the result in the console:

ts-node app.ts
Typescript sort array of objects by property
Typescript sort array of objects by property

This is an example of Typescript sort array of objects by property

Conclusion

In this typescript tutorial, we saw what is sort method is, and how we can use the sort method in typescript. So here are the examples listed below that we cover:

  • typescript sort array
  • typescript sort array alphabetically
  • typescript sort array strings
  • typescript sort associative array
  • typescript sort array by date
  • typescript sort array by number property
  • typescript sort array by name
  • typescript sort array by two properties
  • typescript sort array based on another array
  • typescript sort array alphanumeric
  • typescript sort array by boolean property
  • typescript sort array by index
  • typescript sort array of objects by date descending
  • typescript sort array of objects by property alphabetically
  • typescript sort array of objects by property

You may also like:

>