Last active
June 1, 2021 11:55
-
-
Save mdmoin7/13828acc95b3bf6c32eb98b9e7a6c581 to your computer and use it in GitHub Desktop.
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
/* | |
*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; | |
} | |
} |
@mdmoin7 No, the issue is the same whether or not the user passes a value to caseInsensitivity
. You can confirm this because the caseInsensitivity
is initialized as false
, so unless you pass a value of true
, it will be false
.
The issue is not related to whether the user provides a sorting column name, to be clear.
For example, the issue will appear if you do the following call:
*ngFor="let item of items|sortBy:false:'asc':'keyToSortOn';
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gcko thanks for the clarity, what i think here seems to be a problem when user doesn't provide sorting column name, correct me if I'm wrong. So in that case does placing sensitivity argument last in sequence to pipe help!!