Solution
function countStringOccurrences(str) {
let occurrence = {};
Array.from(str).forEach(char => {
let currentCount = occurrence[char] || 0;
occurrence[char] = currentCount + 1;
});
console.log(occurrence);
return occurrence;
}
countStringOccurrences("hello");
countStringOccurrences("👍😉😉👍");
Result
Object { h: 1, e: 1, l: 2, o: 1 };
Object { 👍: 2, 😉: 2 }
Top comments (5)
This is a nice, simple algorithm. 👍
I would recommend moving
occurrence
inside the function, as it is currently shared and accumulating changes across multiple calls. You are already returningoccurrence
from the function, you just aren't using the output directly.Also, don't be afraid to use longer, clearer names.
countStringOccurrences
is just fine. When working with an isolated example like this the difference is negligible, but the mental overhead of remembering what all the abbreviations are supposed to mean adds up as the program grows.Thanks for your feedback, I have corrected it.
Unfortunately this doesn't work very well...
Try your function with this string: 😉🏝️👍
I corrected it, thanks.
Thanks for testing it, I will look into it.
Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more