Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of objects in typescript?

How do I sort an array of objects in TypeScript?

Specifically, sort the array objects on one specific attribute, in this case nome ("name") or cognome ("surname")?

/* Object Class*/ export class Test{      nome:String;      cognome:String; }  /* Generic Component.ts*/ tests:Test[]; test1:Test; test2:Test;  this.test1.nome='Andrea'; this.test2.nome='Marizo'; this.test1.cognome='Rossi'; this.test2.cognome='Verdi';  this.tests.push(this.test2); this.tests.push(this.test1); 

thx!

like image 338
Maurizio Rizzo Avatar asked Apr 09 '17 19:04

Maurizio Rizzo


People also ask

How do you sort an array of objects in TypeScript?

Array. sort() function sorts an Array. The Sort() function will sort array using the optional compareFunction provided, if it is not provided Javascript will sort the array object by converting values to strings and comparing strings in UTF-16 code units order.

How do you sort an array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do I sort a collection in TypeScript?

Use the sort() Method to Sort Array in TypeScript Sorting is done using the sort() method. This method sorts the elements present in the array and returns the sorted string elements as an output to the user. The sort() method returns the result in ascending order by default.


2 Answers

It depends on what you want to sort. You have standard sort funtion for Arrays in JavaScript and you can write complex conditions dedicated for your objects. f.e

var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => {     if (obj1.cognome > obj2.cognome) {         return 1;     }      if (obj1.cognome < obj2.cognome) {         return -1;     }      return 0; }); 
like image 105
Jaroslaw K. Avatar answered Sep 19 '22 11:09

Jaroslaw K.


Simplest way for me is this:

Ascending:

arrayOfObjects.sort((a, b) => (a.propertyToSortBy < b.propertyToSortBy ? -1 : 1)); 

Descending:

arrayOfObjects.sort((a, b) => (a.propertyToSortBy > b.propertyToSortBy ? -1 : 1)); 

In your case, Ascending:

testsSortedByNome = tests.sort((a, b) => (a.nome < b.nome ? -1 : 1)); testsSortedByCognome = tests.sort((a, b) => (a.cognome < b.cognome ? -1 : 1)); 

Descending:

testsSortedByNome = tests.sort((a, b) => (a.nome > b.nome ? -1 : 1)); testsSortedByCognome = tests.sort((a, b) => (a.cognome > b.cognome ? -1 : 1)); 
like image 21
jbdeguzman Avatar answered Sep 21 '22 11:09

jbdeguzman