如何使用localeCompare根据标记对名称进行排序?

时间:2019-02-27 05:16:42

标签: java angular sorting

我有一个数组列表,其中包含学生的姓名和数学上的个人分数。为此,我只想使用localeCompare并根据其标记以升序和降序排列它们。并在按各自的类别单击时按升序排列名称图标。 在Students.ts中

export class Student{
name:string;
maths:number;
}

在.ts

allStudents : Student[]=[
{name:'James',maths:38},
{name:'Kary',maths:83},
{name:'Bob',maths:93},
{name:'Pam',maths:33},
{name:'Steve',maths:75},
{name:'Williams',maths:61},
{name:'Julis',maths:68},
{name:'Matt',maths:52}
];

showStudents:Student[]=[];
compratehigh(a,b):number{ 
var n=a.localeCompare(b);
return n;

 }
  compratelow(x:Student,y:Student):number{
var x1=x.maths;
var y1=y.maths;
return x.localeCompare(y);
 }

以html

<div class="container">
<h4>Students of V-B</h4>
<div class="row">
<div class="col-4  bg-dark text-light">Name</div> 
<div class="col-1 fa fa-sort bg-primary" (click)="compratehigh()"></div>
<div class="col-4  bg-dark text-light fa fa-sort">Maths</div>
<div class="col-1 fa fa-sort bg-primary" (click)="compratelow()"></div>
<div class="row" *ngFor="let st of showStudents">
<div class="col-3 border">{{st.name}}</div>
<div class="col-3 border">{{st.maths}}</div>
</div>

这是我本可以做的,但是.ts文件中有错误,请帮助我.. !!

1 个答案:

答案 0 :(得分:0)

在.ts

 showStudents:Student[]=[];
 sort(sortby:number){
 this.showStudents=[...this.allStudents];
 if(sortby==0)
 this.showStudents.sort(this.compratehigh);
if(sortby==1)
 this.showStudents.sort(this.compratelow);
}
compratehigh(x:Student,y:Student):number{ 
var x1=x.name;
var y1=y.name;
return x1.localeCompare(y1);
}
compratelow(x:Student,y:Student):number{
var x1=x.maths;
var y1=y.maths;
return x1-y1;
}

以html

<div class="container">
<h4>Students of V-B</h4>
<div class="row">
<div class="col-4  bg-dark text-light">Name</div> 
<div class="col-1 fa fa-sort bg-primary" (click)="sort(0)"></div>
<div class="col-4  bg-dark text-light ">Maths</div>
<div class="col-1 fa fa-sort bg-primary" (click)="sort(1,2)"></div></div>
<div class="row" *ngFor="let st of showStudents">
<div class="col-5 border">{{st.name}}</div>
<div class="col-5 border">{{st.maths}}</div>

</div>
</div>