typescript - Angular 4 の OrderBy パイプが、名前が数字で終わる場合にソートしない
数字で終わる名前をソートするためにパイプを使いたいです。
カスタムパイプを使用しており、期待通りの結果が得られています
- $リンゴの果物-記号
- 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;
}
}
回答 #1
自然な数の並べ替えには、比較関数として Intl.Collator を使用してください。
https://developer.mozilla.org/ja/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:英数字文字列の自然なソート
