Count the occurrence of a character in a string - Javascript

dindustack

Chinwendu Agbaetuo

Posted on July 10, 2024

Count the occurrence of a character in a string - Javascript

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("👍😉😉👍");
Enter fullscreen mode Exit fullscreen mode

Result

Object { h: 1, e: 1, l: 2, o: 1 };
Object { 👍: 2, 😉: 2 }
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
dindustack
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.

Related