2

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

enter image description here

3 Answers 3

6

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)' ]
Sign up to request clarification or add additional context in comments.

1 Comment

@Hav - This will be my new goto function for sorting. Thanks!
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)' ]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.