DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on

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

Top comments (5)

Collapse
 
oculus42 profile image
Samuel Rouse

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

Collapse
 
dindustack profile image
Chinwendu Agbaetuo • Edited

Thanks for your feedback, I have corrected it.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Unfortunately this doesn't work very well...

Try your function with this string: 😉🏝️👍

countStrOcc('😉🏝️👍')

console.log(occurrence)

{
  "\ud83d": 2,
  "\ude09": 1,
  "\ud83c": 1,
  "\udfdd": 1,
  "": 1,
  "\udc4d": 1
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dindustack profile image
Chinwendu Agbaetuo

I corrected it, thanks.

Collapse
 
dindustack profile image
Chinwendu Agbaetuo

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