Working with TypeScript, I am dealing with an array of objects that may contain the same values as other objects within the array. For example, the following array consists of objects with the value "intent". My goal is to identify the top 3 most commonly occurring intents:
[
{
"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"
}
]
I am looking for a solution that provides me with a clear output showing the top 3 intents, such as a key/value pair array:
[
{
"intent": "hello",
"occurrences": 4
},
{
"intent": "hi",
"occurrences": 3
},
{
"intent": "yo",
"occurrences": 2
}
]
Below is my attempt at solving this issue:
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);
}
However, this approach only presents an array of the occurrence values without explicitly stating which intent each value corresponds to. Hence, I am struggling to associate the occurrences with their respective intents.
In attempting to resolve this, I explored various answers shared on resources like Stack Overflow:
Get the element with the highest occurrence in an array
Although I tried implementing the solutions provided, I found it challenging to extend the logic to identify multiple occurrences rather than just the singular highest one. There was uncertainty about how to apply the same principles to find subsequent occurrences beyond the first.