Сортировка массива объектов в машинописном тексте?
Как отсортировать массив объектов в TypeScript?
В частности, сортируйте объекты массива по одному конкретному атрибуту, в этом случае nome
("name") или 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);
спасибо!
Ответы
Ответ 1
Это зависит от того, что вы хотите сортировать. У вас есть стандартная функция сортировки для массивов в JavaScript и вы можете написать сложные условия, предназначенные для ваших объектов. Fe
var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => {
if (obj1.cognome > obj2.cognome) {
return 1;
}
if (obj1.cognome < obj2.cognome) {
return -1;
}
return 0;
});
Ответ 2
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;
});
Ответ 3
this.tests.sort(t1,t2)=>(t1:Test,t2:Test) => {
if (t1.nome > t2.nome) {
return 1;
}
if (t1.nome < t2.nome) {
return -1;
}
return 0;
}
Вы пробовали это так?
Ответ 4
[{nome:'abc'}, {nome:'stu'}, {nome:'cde'}].sort(function(a, b) {
if (a.nome < b.nome)
return -1;
if (a.nome > b.nome)
return 1;
return 0;
});
Ответ 5
Вы можете использовать этот метод.
let sortedArray: Array<ModelItem>;
sortedArray = unsortedArray.slice(0);
sortedArray.sort((left, right) => {
if (left.id < right.id) return -1;
if (left.id > right.id) return 1;
return 0;
})
Ответ 6
рассмотрите ваш массив как myArray,
myArray.sort(( a, b ) => a > b ? 1 : 0 )