I've been working with the sortBy
and uniqBy
functions, but I find myself iterating over the array twice when using the combined sortUniqBy
. If you want to check out the code, feel free to click on this link to the codesandbox. Here's a snippet of the code:
export const sortBy = <T>(o: T[], selector: (item: T) => any): T[] => {
const result = o.slice(0);
result.sort((x, y) => {
const a = selector(x);
const b = selector(y);
return a > b ? 1 : a < b ? -1 : 0;
});
return result;
};
export const uniqBy = <T>(o: T[], selector: (item: T) => any): T[] => {
const ret: T[] = [];
const set = new Set<T>();
o.forEach((s) => {
const value = selector(s);
if (set.has(value) === false) {
set.add(value);
ret.push(s);
}
});
return ret;
};
export const sortedUniqBy = <T>(o: T[], selector: (item: T) => any): T[] => {
return uniqBy(sortBy(o, selector), selector);
};
sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); // [1.1, 2.3]
My question is, is there a way to efficiently sort and remove duplicates in a single loop instead of running two separate loops?