Count the occurrence of a character in a string - Javascript
Chinwendu Agbaetuo
Posted on July 10, 2024
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 }
💖 💪 🙅 🚩
Chinwendu Agbaetuo
Posted on July 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.