angular - 如果名称以数字结尾,Angular 4 OrderBy Pipe 不排序
问题描述
我想使用管道对以数字结尾的名称进行排序。
我使用了自定义管道并按预期获得了结果
- $苹果水果-符号
- 1苹果果实-数字
- 苹果果实-按字母顺序
但如果名称以数字结尾,则不会排序。
现在的结果:
- 苹果果实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 搜索。
推荐阅读
- ios - Swift - 如何获得上传速度而不是下载速度?
- entity-framework-core - 如何在 Entity Framework Core 中控制内存中生成的键值?
- javascript - JS 等价于 Java 的 Collections.unmodifiableCollection
- haskell - 如何运行从 Haskell 源代码生成的 LLVM 位码
- vert.x - MongoClient::save(...) 如何更改文档参数的 _id 字段
- amazon-web-services - 放大 withAuthenticator v/s with withOAuth
- python - Selenium TypeError:this.tabModal 为空
- javascript - 重新加载页面时未显示新添加的字段
- rust - 有没有办法指定多个版本的依赖项对我的库有效?
- java - http 状态 500 - 内部服务器错误(拒绝访问)