Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Why sorting is not working on some of the columns?

I have used column sorting on table. It's working fine on first name and last name column but on dl and dl score it is not working. Can you look into it and help me fix it.

You can view here: https://stackblitz.com/edit/angular-ivy-87hi8i?file=src%2Fapp%2Fapp.component.html

sort(property: any) {
    this.isDesc = !this.isDesc;
    this.column = property;
    let direction = this.isDesc ? 1 : -1;
    this.allUser.sort(function(
      a: { [x: string]: number },
      b: { [x: string]: number }
    ) {
      if (a[property] < b[property]) {
        return -1 * direction;
      } else if (a[property] > b[property]) {
        return 1 * direction;
      } else {
        return 0;
      }
    });
  }

markup

<tr>
<th *ngIf="!isEdit">Edit</th>
<th [ngClass]="{pointer: true, active:column=='first_name',desc:isDesc, asc:!isDesc}"
(click)="sort('first_name')">First Name</th>
<th [ngClass]="{pointer: true, active:column=='last_name',desc:isDesc, asc:!isDesc}"
(click)="sort('last_name')">Last Name</th>
<th>Email</th>
<th>Gender</th>
<th>DOB</th>
<th>Impact</th>
<th>Score</th>
<th [ngClass]="{pointer: true, active:column=='dl',desc:isDesc, asc:!isDesc}" (click)="sort('dl')">
DL</th>
<th [ngClass]="{pointer: true, active:column=='co_score',desc:isDesc, asc:!isDesc}"
(click)="sort('co_score')">DL Score</th>
<th></th>
</tr>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You declare your sort method like:

 this.allUser.sort(function(
      a: { [x: string]: number },
      b: { [x: string]: number }
    )

You're saying that all objects in your array has keys that all return numbers.

So when you sort on first_name prop it finds values like A Male when doing a['first_name'], which is not a number at all, so clearly that's a logical problem. The sorting works for it in runtime anyway since javascript can sort strings like this.

But when you sort on dl, that property does not even exist on your objects, so it's comparing undefined with undefined (a['dl']), which are equal so no sorting will happen.

So ensure to populate your objects with a value for property dl if you want to sort on it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...