Angular 4 如果名称以数字结尾,OrderBy 管道不排序
Angular 4 OrderBy Pipe not sorting if name ends with number
我想用管道对以数字结尾的名字进行排序。
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 搜索返回此 post。
Javascript : natural sort of alphanumerical strings
我想用管道对以数字结尾的名字进行排序。
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 搜索返回此 post。
Javascript : natural sort of alphanumerical strings