Created
April 29, 2021 07:18
-
-
Save osahner/5ea6609f109ee3bc5c6cb5a114f474b1 to your computer and use it in GitHub Desktop.
Sort array (using Intl.Collator)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core'; | |
/* | |
*ngFor="let o of someArry | sortArray:'desc'" | |
*/ | |
@Pipe({ | |
name: 'sortArray', | |
}) | |
export class SortArrayPipe implements PipeTransform { | |
collator: Intl.Collator; | |
constructor(@Inject(LOCALE_ID) private localeId: string) { | |
this.collator = new Intl.Collator(this.localeId, { numeric: true, sensitivity: 'base' }); | |
} | |
transform(value: any[], order = 'asc'): any[] { | |
if (!value || value.length <= 1) { | |
return value; | |
} | |
return [...value].sort((a, b) => | |
order === 'asc' ? this.collator.compare(a, b) : this.collator.compare(b, a) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment