Skip to content

Instantly share code, notes, and snippets.

@ruslanguns
Created March 3, 2020 14:53
Show Gist options
  • Save ruslanguns/082f888c855c367ba9fe6f17ec9bb99a to your computer and use it in GitHub Desktop.
Save ruslanguns/082f888c855c367ba9fe6f17ec9bb99a to your computer and use it in GitHub Desktop.
Angular pipe to sort an array of ngFor
/*
*ngFor="let c of oneDimArray | sortBy:'asc'"
*ngFor="let c of arrayOfObjects | sortBy:'asc':'propertyName'"
*/
import { Pipe, PipeTransform } from '@angular/core';
import { orderBy } from 'lodash';
@Pipe({ name: 'sortBy' })
export class SortByPipe implements PipeTransform {
transform(value: any[], order = '', column: string = ''): any[] {
if (!value || order === '' || !order) { return value; } // no array
if (!column || column === '') { return sortBy(value); } // sort 1d array
if (value.length <= 1) { return value; } // array with only one item
return orderBy(value, [column], [order]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment