angular - 在 typescript 中对一组对象进行排序?

标签 angular sorting typescript

如何在 TypeScript 中对对象数组进行排序?

具体来说,根据一个特定属性对数组对象进行排序,在本例中为 nome(“姓名”)或 cognome(“姓氏”)?

/* 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);

谢谢!

最佳答案

这取决于您要排序的内容。您在 JavaScript 中为 数组 提供了标准的排序 函数,并且您可以编写专用于您的对象的复杂条件。 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;
});

关于angular - 在 typescript 中对一组对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43311121/

相关文章:

c# - 从另一个集合的内容中过滤一个项目集合

javascript - Django 和 Angular 2 错误 {dataService : undefined}

python - 数据操作 - 当值为字母数字时排序索引

c - 对二维数组进行排序,使最大的元素位于主对角线上

javascript - 如何获取 Angular 中可见元素的连续索引并忽略隐藏元素 *ngFor 的索引?

javascript - 为什么 TypeScript 需要 "declaration files"才能使用外部库?

angular - 打开模式时留在同一页面

node.js - 由于 Node.js 和 Angular 运行在不同的本地主机上,如何在 Angular 中使用 Nodemailer 电子邮件验证的路由?

angular - 如何以 Angular 格式化来自数据库的日期

angular - 使用 { dispatch : false } 进行 NGRX 效果测试