我有以下类的数组
export class Tests {
id: number;
name: string;
createdAt: any;
succress: boolean;
constructor(id: number, name: string, createdAt: any, success: boolean) {
this.id = id;
this.name = name;
this.createdAt = createdAt;
this.succress = success;
}
}
我想按成功值对其进行排序(顶部为假,底部为真(。我该怎么做?
我试过了
this.tests.sort((a,b)=> b.succress - a.succress);
但是什么也没做
您可以按布尔值排序,如下所示:
this.tests.sort((a, b) => {
if (a.succress === b.succress) {
return 0;
}
if (a.succress) {
return -1;
}
if (b.succress) {
return 1;
}
});
也许是这样的?
[false,true,false,true]
.sort(
(a,b)=>
(a===b)?0
:(a===true)?1:-1)
您可以使用 lodash sortBy 函数轻松实现此目的
_.sortBy(this.users,['succress'])
现场演示