我有以下物件:
export namespace Data {
export type AsObject = {
a: string,
b: string,
c: string,
d: number,
}
}
我需要從 Data.AsObject[] 中找到最頻繁的字串 Data.AsObject.a。有人可以分享打字稿中的代碼嗎?謝謝,
uj5u.com熱心網友回復:
您沒有解釋在陣列為空或出現平局的情況下會發生什么,因此我使用以下條件實作了它:
- 空陣列會拋出錯誤
- 平局將只回傳一個(首先出現的那個)
如果要更改其中任何一個的行為,則需要對其進行修改。
它還被實作,以便您可以找到任何其他道具的最大出現次數:只需將指定的鍵更改為第二個引數。
TS游樂場
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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419741.html
標籤:
上一篇:陳述句如何防止多載?
