Count the occurrence of a character in a string - Javascript

Chinwendu Agbaetuo - Jul 10 - - Dev Community

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
. . . . . . . . . . . . . . . . . . .