I have an array of objects of the following form:
arr[0] = { \'item1\' : 1234, \'item2\' : \'a string\' };
I sort it first by \'item1\'>
I'm using this helper in TypeScript:
// Source
type ComparatorSelector = (value: T, other: T) => number | string | null;
export function createComparator(...selectors: ComparatorSelector[]) {
return (a: T, b: T) => {
for (const selector of selectors) {
const valA = selector(a, b);
if (valA === null) continue;
const valB = selector(b, a);
if (valB === null || valA == valB) continue;
if (valA > valB) return 1;
if (valA < valB) return -1;
}
return 0;
};
}
// Usage:
const candidates: any[] = [];
// ...
candidates.sort(createComparator(
(x) => x.ambiguous,
(_, y) => y.refCount, // DESC
(x) => x.name.length,
(x) => x.name,
));