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!
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));
const sorted = unsortedArray.sort((t1, t2) => {
const name1 = t1.name.toLowerCase();
const name2 = t2.name.toLowerCase();
if (name1 > name2) { return 1; }
if (name1 < name2) { return -1; }
return 0;
});