Using TypeScript I have an array of objects which may contain the same values as other objects in the array. The following array, for example, contains objects that have the value "intent". I would like the find 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'm trying to get some sort of result that will easily show me the top 3, maybe a key/value pair array or something:
[
{
"intent": "hello",
"occurrences": 4
},
{
"intent": "hi",
"occurrences": 3
},
{
"intent": "yo",
"occurrences": 2
}
]
Below is my attempt at a solution:
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 only returns an array of the occurrence values and not the name of the intent themselves. So I am struggling to find with the array which value belongs to which intent.
I tried following the answers posted in this solution:
Get the element with the highest occurrence in an array
However, I couldn't figure out how to find n
occurrences, instead just the top occurrence. I wasn't sure how to use that logic to carry on to find the next few occurrences.