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;
});
Firstly, count the occurrences of each name in the array.
Secondly, convert it into an object with the desired format of name and their matches.
const names = ["tony", "tony", "tony", "tony", "kassandra", "tony", "tony", "kassandra"];
const counts = {};
//1.
names.forEach(name => {
if (counts[name]) {
counts[name] += 1;
} else {
counts[name] = 1;
}
});
//2.
const result = Object.keys(counts).map(name => {
return {
name: name,
matches: counts[name]
};
});
console.log(result);
If you want to use .reduce() approach to counting occurrences of names:
const counts = names.reduce((acc, name) => {
acc[name] = (acc[name] || 0) + 1;
return acc;
}, {});
Another approach to convert occurrences back into an object using Object.entries()
Object.entries(counts).map(([name, matches]) => ({ name, matches }));
Two approaches combined:
const names = ["tony", "tony", "tony", "tony", "kassandra", "tony", "tony", "kassandra"];
const counts = names.reduce((acc, name) => {
acc[name] = (acc[name] || 0) + 1;
return acc;
}, {});
const result = Object.entries(counts).map(([name, matches]) => ({ name, matches }));
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With