在 Angular/Typescript 中用整数和字母对数组进行排序 [英] Sort an array with integers and letters alphabetic in Angular / Typescript
本文介绍了在 Angular/Typescript 中用整数和字母对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我打算做什么
我尝试像这样对数组进行排序...
- 1
- 2
- 2(a)
- 2(b)
- 2(b) #AsimpleName
- 2(b) #NameWithN
- 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();});
我认为的循环
<strong>{{house.number }}</strong>...
'number'
在这种情况下是没有字母的干净数字.我将这封信存储在一个单独的 firebase 条目中.但如果需要,肯定可以将它们存储在同一个中.
附加信息:我正在使用 VadimDez 的 ngx-orderBy-pipe:
解决方案
这个函数应该可以解决问题:
function sortData(array: Array): Array{return array.sort((a, b) => a
这里是使用示例:
const sorted = sortData(['4(a)', 4, 3, '2(b) #NameWithN', '2(b) #AsimpleName']);排序//[ '2(b) #AsimpleName', '2(b) #NameWithN', 3, 4, '4(a)' ]
What I plan to do
I try to sort an array like this...
- 1
- 2
- 2(a)
- 2(b)
- 2(b) #AsimpleName
- 2(b) #NameWithN
- 3
- 4
- 4(a)
- ...
... in Angular2.
My Current Code
Component
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();
});
The loop in my view
<ion-item-sliding *ngFor="let house of streetDetailData | async | orderBy: 'number':false" #slidingItem>
<strong>{{ house.number }}</strong> ...
'number'
in this case is the clean number without letter. I store the letter in a separate firebase entry. But sure would be possible to store them in the same if needed.
Additional information: I'm using the ngx-orderBy-pipe by VadimDez: https://github.com/VadimDez/ngx-order-pipe
The current result
解决方案
This function should do the trick:
function sortData(array: Array<number | string>): Array<number | string> {
return array.sort((a, b) => a < b ? -1 : 1);
}
And here is use example:
const sorted = sortData(['4(a)', 4, 3, '2(b) #NameWithN', '2(b) #AsimpleName']);
sorted // [ '2(b) #AsimpleName', '2(b) #NameWithN', 3, 4, '4(a)' ]
这篇关于在 Angular/Typescript 中用整数和字母对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文