2

I have a question when I build sort pipe in Angular2 here is my pipe code:

enter image description here

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sort'
})
export class SortPipe implements PipeTransform {

  transform(value: any, propName: string): any {

    return value.sort((a,b)=> {
      return a[propName]-b[propName];
      // if(a[propName]>b[propName]) {
      //   return 1;
      // } else {
      //   return -1;
      // }
    });        
  }      
}

When I use the code in comments, the pipe works, but when I use return a [propName]-b[propName]; it is not working;

3
  • chances are, youre trying to subtract a string from a string by the looks if it Commented Jan 31, 2018 at 15:05
  • 1
    And have you seen this: angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe It highly recommends against building pipes that sort or filter. Do it in your component class instead. I have an example of a filter here: blogs.msmvps.com/deborahk/filtering-in-angular You could do something similar for the sort. Commented Jan 31, 2018 at 15:07
  • @DeborahK that recommendation provides no evidence. I have used such pipes in multiple production apps without issue. Commented Feb 3, 2018 at 17:28

3 Answers 3

1

For sort to work, you must return an integer (see reference). Are you sure, that subtracting your properties will always return these values?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply, I want to try this because I saw w3schools.com/js/tryit.asp?filename=tryjs_array_sort2
@Mia I edited my answer to reflect an error I have made. You can subtract numbers, but your answer also has to be a number. So you must be sure, that every object has this param (you cannot subtract undefined), and return value can be casted to number (for example 5 - null will yield 5, but 5 - 'st' will yield NaN).
0

Depends on what you are sorting. If the value is a number it should work. If it's a string then a NaN is returned. Second solution is better.

Comments

-1

This code selects the property of the list of items objects passed in by the pipe and takes into consideration null values.

Below you can see what the pipe will look like with the *ngFor:

<tr *ngFor="let item of Clients | sort: sortType: sortDirection">

Below you can see when the column header is clicked, the arrows change direction of the arrow and make the sort output ascending or descending within the sort pipe.

<th>
        <div class="d-flex flex-row hoverOver">
          <span class="text-nowrap">Quantity</span>
          <i class="fa hoverTrans align-self-center mx-1" [ngClass]="{'fa-arrows-v': column != 'created',
            'fas fa-long-arrow-up': !sortDirection,
            'fas fa-long-arrow-down': sortDirection }" (click)="sortType = 'qty'; sortDirection = !sortDirection">
          </i>

Below is the Sort Pipe:

transform(items: any, sortType: any, sortDirection: any): any {

    const direction = sortDirection ? -1 : 1;

    items.sort((a, b) => {
      if (a[sortType] < b[sortType] || (a[sortType] === null && b[sortType] !== null) || (a[sortType] === "" && b[sortType] !== null)) {
        return -1 * direction;
      } else if (a[sortType] > b[sortType] || (a[sortType] !== null && b[sortType] === null) || (a[sortType] !== null && b[sortType] === "")) {
        return 1 * direction;
      } else {
        return 0;
      }
    });

    return items;
  }

2 Comments

Don't use images, instead write the code in code blocks. Is more readable
Thanks for the feedback I have updated my answer for readability.

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.