如何在打字稿中获取字符串数组中出现频率最高的元素

How to get most frequent element on a string array in typescript

我有以下对象:

export namespace Data {
  export type AsObject = {
    a: string,
    b: string,
    c: string,
    d: number,
  }
}

并且我需要从 Data.AsObject[] 中找到出现频率最高的字符串 Data.AsObject.a。 有人可以用打字稿分享代码吗? 谢谢,

你没有解释在数组为空或最大出现次数相同的情况下应该发生什么,所以我用这些条件实现它:

  • 空数组会抛出错误
  • 平局只会返回一个(先出现的那个)

如果你想改变其中任何一个的行为,你需要修改它。

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.

TS Playground

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"