¿Cómo clasifico una matriz de objetos en TypeScript?
Específicamente, ordenar los objetos de la matriz en un atributo específico, en este caso nome ("nombre") o cognome ("apellido").
/* 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);¡gracias!
Depende de lo que quieras ordenar. Tiene una función de clasificación estándar para Array s en JavaScript y puede escribir condiciones complejas dedicadas a sus objetos. fe
var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => { if (obj1.cognome > obj2.cognome) { return 1; } if (obj1.cognome < obj2.cognome) { return -1; } return 0; });La forma más simple para mí es esta:
Ascendente:
arrayOfObjects.sort((a, b) => (a.propertyToSortBy < b.propertyToSortBy ? -1 : 1));Descendente:
arrayOfObjects.sort((a, b) => (a.propertyToSortBy > b.propertyToSortBy ? -1 : 1));En tu caso, Ascendente:
testsSortedByNome = tests.sort((a, b) => (a.nome < b.nome ? -1 : 1)); testsSortedByCognome = tests.sort((a, b) => (a.cognome < b.cognome ? -1 : 1));Descendente:
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; });