I need to iterate over an array of strings, count the occurrences of each string, and return a object with the value and the number of occurrences.
I'm trying to use the array reduce function to achieve such thing, but, despite the attempts, I haven't been able to achieve that yet.
So I have the following:
["tony", "tony", "tony", "tony", "kassandra", "tony", "tony", "kassandra"]
I need the output:
[{ name: "tony", matches: 6 }, { name: "kassandra", matches: 2 }]
What should I use to obtain the above output?
I have tried the following:
const names = nameList.map((user) => user.name);
const reduce = names.reduce((p, c) => {
if (p == c) {
return { name: p, matches: `idk what put here yet` };
}
return c;
});