使用 TypeScript 我有一个对象数组,其中可能包含与数组中其他对象相同的值。例如,以下数组包含具有值“intent”的对象。我希望找到前 3 个最常发生的意图:
[
{
"intent": "hello",
"other_value": "blah"
},
{
"intent": "hello",
"other_value": "blahblah"
},
{
"intent": "hi",
"other_value": "anothervalue"
},
{
"intent": "hello",
"other_value": "what?"
},
{
"intent": "hello",
"other_value": "eh?"
},
{
"intent": "hi",
"other_value": "okthen"
},
{
"intent": "yo",
"other_value": "alright"
},
{
"intent": "hi",
"other_value": "yes"
},
{
"intent": "yo",
"other_value":"yawhat?"
},
{
"intent": "hey",
"other_value": "meh"
}
]
我正在尝试获得某种可以轻松显示前 3 个结果的结果,可能是键/值对数组或其他内容:
[
{
"intent": "hello",
"occurrences": 4
},
{
"intent": "hi",
"occurrences": 3
},
{
"intent": "yo",
"occurrences": 2
}
]
以下是我尝试的解决方案:
function top3(array) {
let results = [];
array.forEach(item => {
if (results[item.intent] != null) {
results[item.intent] += 1
} else {
results[item.intent] = 1;
}
});
results = results.sort();
return results.slice(0, 3);
}
但是,这仅返回出现值的数组,而不是意图本身的名称。所以我很难用数组找到哪个值属于哪个意图。
我尝试按照此解决方案中发布的答案进行操作:
Get the element with the highest occurrence in an array
但是,我不知道如何查找 n
次出现,而只是查找最上面的出现。我不确定如何使用该逻辑继续查找接下来的几次出现。
最佳答案
您可以首先通过构建一个对象数组来获取具有计数的对象,然后按出现次数
对其进行降序排序,然后对数组进行切片以仅获取前三个元素。
var data = [{ intent: "hello", other_value: "blah" }, { intent: "hello", other_value: "blahblah" }, { intent: "hi", other_value: "anothervalue" }, { intent: "hello", other_value: "what?" }, { intent: "hello", other_value: "eh?" }, { intent: "hi", other_value: "okthen" }, { intent: "yo", other_value: "alright" }, { intent: "hi", other_value: "yes" }, { intent: "yo", other_value: "yawhat?" }, { intent: "hey", other_value: "meh" }],
count = data
.reduce((r, { intent }) => {
r[intent] = r[intent] || { intent, occurences: 0 };
r[intent].occurences++;
return r;
}, {}),
top3 = Object
.values(count)
.sort((a, b) => b.occurences - a.occurences)
.slice(0, 3);
console.log(top3);
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何使用 Typescript/JS 查找数组中对象值出现的前 n 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50045690/