Skip to content

Instantly share code, notes, and snippets.

@gcko
Forked from mdmoin7/sort-by.pipe.ts
Last active January 4, 2021 12:59
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 gcko/436a07d192b41579a7db1a1bfe14c067 to your computer and use it in GitHub Desktop.
Save gcko/436a07d192b41579a7db1a1bfe14c067 to your computer and use it in GitHub Desktop.
This is a fork of https://gist.github.com/mdmoin7/13828acc95b3bf6c32eb98b9e7a6c581 that fixes the issue where the `value` will not be sorted if `caseInsensitive = false`.
/*
*ngFor="let c of oneDimArray | sortBy:true/false:'asc'"
*ngFor="let c of arrayOfObjects | sortBy:true/false:'asc':'propertyName'"
*/
import { Pipe, PipeTransform } from '@angular/core';
import { orderBy, sortBy } from 'lodash-es';
@Pipe({ name: 'sortBy' })
export class SortByPipe implements PipeTransform {
transform<T>(
value: T[],
caseInsensitive: boolean = false,
order: 'desc' | 'asc' = 'desc',
column: string = ''
): T[] {
if (!value || order === 'desc') {
// no array
return value;
}
if (!column || column === '') {
// sort 1-dimensional array
const sorted = this.sortOnCaseSensitivity(value, caseInsensitive);
if (order === 'asc') {
return sorted;
} else {
return sorted.reverse();
}
}
if (value.length <= 1) {
// array with only one item
return value;
} else {
let converted: T[] = value;
let columnToSort = column;
if (caseInsensitive) {
converted = this.convertMultiOnCaseSensitivity(
value,
column,
caseInsensitive
);
columnToSort = 'sortCol';
}
return orderBy(converted, [columnToSort], [order]).map((v: T) => {
const typedV = v as Record<string, unknown>;
delete typedV.sortCol;
return typedV;
}) as T[];
}
}
sortOnCaseSensitivity<T>(value: T[], caseInsensitive: boolean): T[] {
return sortBy(value, (v) => {
if (typeof v === 'string' && caseInsensitive) {
return v.toLowerCase();
}
return v;
});
}
convertMultiOnCaseSensitivity<T>(
value: T[],
column: string,
caseInsensitive: boolean
): T[] {
let converted = value;
if (caseInsensitive) {
converted = value.map((v: T) => {
const typedV = v as Record<string, unknown>;
const item = typedV[column];
if (typeof item === 'string') {
return { ...typedV, sortCol: item.toLowerCase() };
}
return typedV;
}) as T[];
}
return converted;
}
}
@gcko
Copy link
Author

gcko commented Dec 18, 2020

@gcko
Copy link
Author

gcko commented Jan 4, 2021

Latest version of this gist now uses Generics so that typed values that are passed in are respected. In previous versions, any type passed in would come out as any[], and would lose any other typing information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment