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

标签 angular typescript sorting angular-pipe

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

I have used custom pipe and getting results as expected

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

But it is not sorting if name ends with number.

现在的结果:

  • 苹果果实3
  • 苹果水果01
  • 苹果果实5
  • 苹果水果02

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;
}
}

最佳答案

使用 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

关于如果名称以数字结尾,Angular 4 OrderBy Pipe 不排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52885797/

相关文章:

javascript - 为什么 JavaScript 对象不会为当前为空的嵌套对象设置值

java - 对可能包含数字的字符串进行排序

matlab - 在matlab上绘制矩阵的点

javascript - 如何过滤对象数组的数组?

Angular Forms 响应式(Reactive) - 交叉控制验证

angular - ngSubmit.emit() 不会改变 formGroup 的提交属性

c++ - 使用排序函数以链式方式对元组 vector 进行排序

angular - 从 3.1 升级后.NET Core 5.0 Azure 部署 CORS 问题

class - typescript : unexpected reserved word in PHPStorm

具有动态参数的 Angular Factory Provider