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!
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.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
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.
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; });
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With