0

As you can see in the .ts file that I am trying to do the sorting the Array which is in Table Form. The Array is in Static

list.component.ts

sort(){
    this.Homes.sort(function(a,b){
      if(a>b)
        return 1
      if(a<b)
        return -1
      return 0;
    });
  }

list.component.html

            <table class="table table-striped">
                <thead>
                    <tr>
                        <th scope="col" (click)="sort()">Name</th>
                        <th scope="col">Age</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody *ngFor="let item of Homes">
                    <!-- <tr *ngIf="item.Age < 22"> -->
                    <tr>
                        <td scope="row">{{ item.Name }}</td>
                        <td class={{item.ColorClass}}>{{item.Age}}</td>
                        <td class="fa fa-trash" (click)="delete(item)"></td>
                        <td class="fa fa-pencil" (click)="edit(item)" data-toggle="modal" data- 
                      target="#myModal"></td>
                    </tr>
                </tbody>
            </table>

2 Answers 2

2

You have to provide object property name i.e.

sort(){
    this.Homes.sort(function(a,b){
      if(a.Name > b.Name)
        return 1
      if(a.Name < b.Name)
        return -1
      return 0;
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

2

Based on Mukesh Vadodariya response, but simpler

sort(){
    this.Homes.sort(function(a,b){
      return a.Name.localCompare(b.Name);
    });
  }

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.