Home > Enterprise >  Angular pipe - Sorting without case sensitive
Angular pipe - Sorting without case sensitive

Time:09-30

I got this sorting pipe created in Angular project below. The result is enter image description here I need to sort "Accos, David pt., DIILL," The uppercase seems issue here.

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

@Pipe({
  name: 'orderBy',
})
export class OrderByPipe implements PipeTransform {
  transform(array: any[], field: string): any[] {
    if (!array) return array;

    array = [...array];
    array.sort((a: any, b: any) => {
      if (a[field] < b[field]) {
        return -1;
      } else if (a[field] > b[field]) {
        return 1;
      } else {
        return 0;
      }
    });

    return array;
  }
}
 <ng-select
              [items]="accounts$ | async | orderBy: 'businessName'"
              [(ngModel)]="AccownerId"
              bindLabel="businessName"
              bindValue="id"
              [searchable]="false"
              id="Accowner"
            >
            </ng-select>

CodePudding user response:

You can use this case insensitive comparison:

const options  = ["DIILL", "Accos", "David pt."];
        
options.sort((a: any, b: any) => {
      return a.toLowerCase()
              .localeCompare(b.toLowerCase());
  });
        
console.log(options);//["Accos", "David pt.", "DIILL"]
  • Related