Skip to content

Instantly share code, notes, and snippets.

@mdmoin7
Last active June 1, 2021 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mdmoin7/13828acc95b3bf6c32eb98b9e7a6c581 to your computer and use it in GitHub Desktop.
Save mdmoin7/13828acc95b3bf6c32eb98b9e7a6c581 to your computer and use it in GitHub Desktop.
/*
*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";
@Pipe({ name: "sortBy" })
export class SortByPipe implements PipeTransform {
transform<T>(
value: T[],
caseInsensitive = false,
order = "",
column: string = ""
): T[] {
if (!value || order === "" || !order) {
return value;
} // no array
if (!column || column === "") {
const sorted = this.sortOnCaseSensitivity(value, caseInsensitive);
if (order === "asc") {
return sorted;
} else {
return sorted.reverse();
}
} // sort 1d array
if (value.length <= 1) {
return value;
} // array with only one item
else {
const converted = this.convertMultiOnCaseSensitivity(
value,
column,
caseInsensitive
);
return orderBy(converted, ["sortCol"], [order]).map(v => {
delete v["sortCol"];
return v;
});
}
}
sortOnCaseSensitivity<T>(value: T[], caseInsensitive: boolean): T[] {
return sortBy(value, (v: T) => {
if (typeof v === "string" && caseInsensitive) {
return v.toLowerCase();
}
return v;
});
}
convertMultiOnCaseSensitivity<T>(
value: T[],
column: string,
caseInsensitive: boolean
): T[] {
let converted = value.map((v: T) => ({ ...v, sortCol: v[column] }));
if (caseInsensitive) {
converted = value.map((v: T) => {
if (typeof v[column] === "string") {
return { ...v, sortCol: v[column].toLowerCase() };
}
return { ...v, sortCol: v[column] };
});
}
return converted;
}
}
@gcko
Copy link

gcko commented Jan 4, 2021

@mdmoin7 I made a followup revision on my gist here. The latest version now uses Generics so that passed in types are respected. In previous versions, any type passed in would come out as any[], and would lose other typing information.

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