My current use case involves utilizing the following code snippet to effectively sort an array of objects based on specific criteria. This function allows for sorting in either ascending or descending order, and supports sorting by one or multiple keys. I initially came across this solution on stackoverflow a few weeks ago and made some modifications to tailor it to my needs. Additionally, I have implemented an enum to enhance the safety of the code. While the implementation provided is in typescript, it can easily be converted to Javascript after removing the type annotations and interfaces.
export declare enum EOrderBy {
ASC = "ASC",
DESC = "DESC"
}
export interface ISortConfig<T> {
column: keyof T;
order?: keyof typeof EOrderBy;
map?: itemMap;
}
export const sortByValues = <T extends object>(
columns: (keyof T | ISortConfig<T>)[]
): ((a: T, b: T) => 0 | 1 | -1) => {
return function (a: T, b: T) {
// Implementation logic
};
};
export const sortArray = <T extends object>(
array: T[],
columns: (keyof T | ISortConfig<T>)[]
) => {
return array.sort(sortByValues<T>(columns));
};
An example illustrating the usage:
interface IObj {
name: string;
prenom: string;
montant: number;
}
const arrobj: IObj[] = [
{
name: "al",
prenom: "jero",
montant: 10,
},
{
name: "al",
prenom: "ale",
montant: 100,
},
{
name: "zozo",
prenom: "aa",
montant: 10,
},
];
// Simple ordering example
console.log(sortArray(arrobj, [{ column: "prenom", order: "ASC" }]));
console.log(sortArray(arrobj, [{ column: "montant", order: "DESC" }]));
// Ordering by several properties (montant DESC followed by name ASC)
console.log(
sortArray(arrobj, [
{ column: "montant", order: "DESC" },
{ column: "name", order: "ASC" },
])
);
// Preparing the orderBy parameter in a variable before passing it to the function
const orderBy: IOrderBy<IObj>[] = [
{ column: "name", order: EOrderBy.DESC },
{ column: "prenom", order: EOrderBy.DESC },
];
console.log(sortArray(arrobj, orderBy));