cfoster5
cfoster5

Reputation: 1826

Sort object array used in *ngFor with directive

Using Angular, I have created a table with a sort directive that sorts the table based on what header is clicked. However, if the input data has any null values, the sort directive will not work properly.

This is my sort function in the directive:

  sortArray (): Array<any> {
    let tempArray: Array<any> = this.data;
    tempArray.sort((a, b) => {
      let aKey = a[this.key];
        let str1: string = a[this.key].toLowerCase();
        let str2: string = b[this.key].toLowerCase();
        if (this.toggleSort) {
          if (str1 < str2) {
            return -1;
          }
          if (str1 > str2) {
            return 1;
          }
        }
        else {
          if (str1 > str2) {
            return -1;
          }
          if (str1 < str2) {
            return 1;
          }
        }
      return 0;
    });
    return tempArray;
  }

How can I get this to work on null values?

I have attached a Stackblitz for this issue.

Upvotes: 1

Views: 122

Answers (1)

Mike Tung
Mike Tung

Reputation: 4821

sortArray (): Array<any> {
    let tempArray: Array<any> = this.data;
    tempArray.sort((a, b) => {
      let aKey = a[this.key];
        let str1: string = a[this.key].toLowerCase();
        let str2: string = b[this.key].toLowerCase();
        if (this.toggleSort) {
          if (!str1 && !str2) {
            return 0;
          } else if (!str1) {
            return 1;
          } else if (!str2) {
            return -1;
          }

          //rest of your logic if neither is null
          if (str1 < str2) {
            return -1;
          }
          if (str1 > str2) {
            return 1;
          }
        }
        else {
          if (str1 > str2) {
            return -1;
          }
          if (str1 < str2) {
            return 1;
          }
        }
      return 0;
    });
    return tempArray;
  }

Upvotes: 1

Related Questions