在 Angular/Typescript 中對包含整數和字母的陣列進行字母排序
我計劃要做的事
我試圖像這樣排序一個陣列……
- 1
- 2
- 2(a)
- 2(b)
- 2(b) #簡單名稱
- 2(b) #帶N的名字
- 3
- 4
- 4(a)
- ...
... 在 Angular2 中。
我目前的程式碼
元件
this.streetDetailRef = this.afDatabase.list('data/users/' + this.currentUserID + '/territory/' + this.sStreet.parentKey + '/' + this.sStreet.key + '/houseNumbers/');
this.streetDetailData = this.streetDetailRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() })).sort();
});
在我看來的迴圈
<ion-item-sliding *ngFor="let house of streetDetailData | async | orderBy: 'number':false" #slidingItem>
<strong>{{ house.number }}</strong> ...
`'number'` 在這種情況下是指不含字母的乾淨數字。我把字母存放在另一個 Firebase 條目裡。但如果需要,當然也可以將它們存放在同一個條目裡。
附加資訊:我正在使用 VadimDez 的 ngx-orderBy-pipe:https://github.com/VadimDez/ngx-order-pipe
當前結果
答案#1
這個函數應該可以解決問題:
function sortData(array: Array<number | string>): Array<number | string> {
return array.sort((a, b) => a < b ? -1 : 1);
}
這裡是一個使用範例:
const sorted = sortData(['4(a)', 4, 3, '2(b) #NameWithN', '2(b) #AsimpleName']);
sorted // [ '2(b) #AsimpleName', '2(b) #NameWithN', 3, 4, '4(a)' ]
答案#2
更新:雖然我的答案可行,但被採納的答案更好,我將在未來使用它。
你可以使用這個簡單的比較函數,並搭配 Typescript 內建的 sort() 函數來得到你想要的答案。
Typescript :
function sortStrings(a: string, b: string) {
a = a.toLowerCase();
b = b.toLowerCase();
return a > b ? 1 : (a < b ? -1 : 0);
}
console.log(['4(a)', '3', '2', '2(b) secondName',
'2(b)firstName','2(b)','2(a)', '4', '1'].sort(sortStrings));
輸出:
[ '1',
'2',
'2(a)',
'2(b)',
'2(b) firstName',
'2(b) secondName',
'3',
'4',
'4(a)' ]
