I have a javascript array as follows:
[
{moodSymbol: "๐"},
{moodSymbol: "๐"},
{moodSymbol: "๐ค"},
{moodSymbol: "๐"},
{moodSymbol: "๐"},
{moodSymbol: "๐คช"},
{moodSymbol: "๐"},
{moodSymbol: "๐คจ"},
{moodSymbol: "๐ค"},
{moodSymbol: "๐ฅฐ"},
{moodSymbol: "๐"},
{moodSymbol: "๐ข"},
]
How can I get the count of each emoji and still keep the moodSymbol key name as such:
const data = [
{
moodSymbol: "๐",
count: 3
},
{
moodSymbol: "๐",
count: 2
},
...
]
I also want the top 5 with the highest count. I tried using reduce and I honestly have been having so much trouble getting this to work with emojis.
You can create an object (hash map) to count each symbol and then generate the results array.
To get the top 5, just sort the result in decending order and then splice the array to have only 5 elements.
let arr = [ {moodSymbol: "๐"}, {moodSymbol: "๐"}, {moodSymbol: "๐ค"}, {moodSymbol: "๐"}, {moodSymbol: "๐"}, {moodSymbol: "๐คช"}, {moodSymbol: "๐"}, {moodSymbol: "๐คจ"}, {moodSymbol: "๐ค"}, {moodSymbol: "๐ฅฐ"}, {moodSymbol: "๐"}, {moodSymbol: "๐ข"}];
let obj = {};
arr.forEach(e => {
obj[e.moodSymbol] = obj[e.moodSymbol] || 0;
obj[e.moodSymbol]++;
});
let res = Object.entries(obj).map(e => ({moodSymbol: e[0], count: e[1]}));
res.sort((a, b) => b.count - a.count).splice(5);
console.log(res);