Skip to content

Instantly share code, notes, and snippets.

@osahner
Created April 29, 2021 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osahner/5ea6609f109ee3bc5c6cb5a114f474b1 to your computer and use it in GitHub Desktop.
Save osahner/5ea6609f109ee3bc5c6cb5a114f474b1 to your computer and use it in GitHub Desktop.
Sort array (using Intl.Collator)
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