I have the following object:
export namespace Data {
export type AsObject = {
a: string,
b: string,
c: string,
d: number,
}
}
And I need to find the most frequent string Data.AsObject.a from Data.AsObject[]. Can someone please share a code in typescript to do it ? Thanks,
You didn't explain what should happen in the case that the array is empty or that there is a tie for greatest occurrence, so I implemented it with these conditions:
You'll need to modify it if you want to change the behavior of either of those.
It's also implemented so that you can find the greatest occurrence of any other prop: just change the specified key as the second argument.
namespace Data {
export type AsObject = {
a: string;
b: string;
c: string;
d: number;
};
}
// If there's a tie, only one is returned
function greatestOccurrence <K extends keyof Data.AsObject>(
arr: Data.AsObject[],
key: K,
): Data.AsObject[K] {
type T = Data.AsObject[K];
const map = new Map<T, number>();
for (const o of arr) {
const item = o[key];
map.set(item, (map.get(item) ?? 0) + 1);
}
const result = [...map].sort(([, a], [, b]) => b - a)[0]?.[0];
if (typeof result === 'undefined') throw new Error('Array is empty');
return result;
}
///// Use like this:
// I'll skip filling out the extra props in this input example:
const items = [
{a: 'hello'},
{a: 'hello'},
{a: 'hola'},
{a: 'willkommen'},
{a: 'bonjour'},
{a: 'hola'},
{a: 'hola'},
] as Data.AsObject[];
const result = greatestOccurrence(items, 'a');
console.log(result); // "hola"