【问题标题】:Angular pipe - Sorting without case sensitive角管 - 排序不区分大小写
【发布时间】:2021-09-30 02:59:03
【问题描述】:

我在下面的 Angular 项目中创建了这个排序管道。结果是 我需要对“Accos, David pt., DIILL”进行排序,大写在这里似乎有问题。

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>

【问题讨论】:

  • 它适用于更新版本...................................... ............................. 导出类 OrderByPipe 实现 PipeTransform { transform(array: any [], field: any): any[] { if (!array) 返回数组;数组 = [...数组]; array.sort((a, b) => a[field].toLowerCase().localeCompare(b[field].toLowerCase()));返回数组; } }

标签: arrays angular sorting


【解决方案1】:

您可以使用这种不区分大小写的比较:

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"]

【讨论】:

  • 谢谢。我已经像这样更新并且现在正在工作。 if (!array) 返回数组;数组 = [...数组]; array.sort((a, b) => a[field].toLowerCase().localeCompare(b[field].toLowerCase()));返回数组;
猜你喜欢
  • 2019-01-31
  • 2020-09-13
  • 2012-06-22
  • 1970-01-01
  • 2014-11-10
  • 2015-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多