Sort an array with integers and letters alphabetic in Angular / Typescript

回眸只為那壹抹淺笑 提交于 2021-02-08 03:42:26

问题


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


回答1:


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)' ]



回答2:


UPDATE: While my answer works, the accepted answer is better and I will adopt it for use in the future.

You can use this simple compare function, along with Typescript's built-in sort() function to get the answers you want.

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));

Output:

[ '1',
  '2',
  '2(a)',
  '2(b)',
  '2(b) firstName',
  '2(b) secondName',
  '3',
  '4',
  '4(a)' ]



回答3:


Using Typescript you can sort any collection which you have. Following is a code sample which might help you. I guess treating your id as string will solve the problem.

let names: [string];
    let numbers: [number];
    names.sort(this.sortByLetter);
    numbers.sort(this.sortByNumber);

sortByLetter(string1: string, string2: string) {
    if (string1 > string2) return 1
    else if (string1 === string2) return 0
    else return -1;
}


sortByNumber(n1: number, n2: number) {
    return n2 - n1;
}


来源:https://stackoverflow.com/questions/47743466/sort-an-array-with-integers-and-letters-alphabetic-in-angular-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!