我想使用管道对以数字结尾的名称进行排序。
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.Collator 作为自然数排序的比较函数。
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 搜索,该搜索返回了这篇文章。
关于如果名称以数字结尾,Angular 4 OrderBy Pipe 不排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52885797/