首页 > 解决方案 > 如果名称以数字结尾,Angular 4 OrderBy Pipe 不排序

问题描述

我想使用管道对以数字结尾的名称进行排序。

我使用了自定义管道并按预期获得了结果

但如果名称以数字结尾,则不会排序。

现在的结果:

JSON

[
{"name": "Apple fruit3"},
{"name": "$Apple fruit"},
{"name": "Apple fruit"},
{"name": "Apple fruit01"},
{"name": "Apple fruit5"},
{"name": "Apple fruit02"},
]

HTML

<div *ngFor='let list of names | appOrderBy : "name" '>
<div>{{list.name}}</div>
</div>

OrderBy 自定义管道

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
     name: 'appOrderBy'
})
export class OrderBy implements PipeTransform {
transform(array: Array<string>, args: string): Array<string>{
array.sort((a: any, b: any) => {
  if (a[args] < b[args]) {
    return -1;
  } else if (a[args] > b[args]) {
    return 1;
  } else {
    return 0;
  }
});
return array;
}
}

标签: angulartypescriptsortingangular-pipe

解决方案


使用 Intl.Collat​​or 作为自然数排序的比较函数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collat​​or

const array = [
  {name: "Apple fruit3"},
  {name: "$Apple fruit"},
  {name: "Apple fruit"},
  {name: "Apple fruit01"},
  {name: "Apple fruit5"},
  {name: "Apple fruit02"},
];

args= 'name';

var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});

array.sort((a, b) => collator.compare(a[args], b[args]));

console.log(array);

我将此答案基于搜索返回此帖子的自然数排序 Google 搜索。

Javascript:自然排序的字母数字字符串


推荐阅读