如果名称以数字结尾,Angular 4 OrderBy管道将不排序

时间:2018-10-19 04:10:12

标签: angular typescript sorting angular-pipe

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

  

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

  • $苹果果实-符号
  • 1个Apple水果-数字
  • 苹果果实按字母顺序
  

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

立即获得结果:

  • 苹果水果3
  • 苹果fruit01
  • 苹果果实5
  • 苹果fruit02

JSON

def findSingleOccurance( arr, n): 

    res = arr[0] 

    # Do XOR of all elements and return 
    for i in range(1,n): 
        res = res ^ arr[i] 

    return res 

HTML

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

通过自定义管道订购

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

1 个答案:

答案 0 :(得分:2)

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator

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 : natural sort of alphanumerical strings