Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find unique characters in a string and the count of their occurrences

I need to count the occurrence of characters in a given string and print out the unique characters and the number of how many times they appeared. So, for example, if I receive a string of ‘HELLO’ it should print out:

H: 1,
E: 1,
L: 2,
O: 1

This is a much-simplified version of a problem, but the answer should put me in the right direction. How can I approach this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance.

>Solution :

My approach to this problem is:

let str = "HELLO";

// An object for the final result {character:count}
let counts = {};

// Loop through the str...
for (let index = 0; index < str.length; ++index) {
  // Get each char
  let ch = str.charAt(index);
  // Get the count for that char
  let count = counts[ch];
  // If we have one, store that count plus one;
  if (count) {
    counts[ch] += 1;
  } else {
    // if not, store one
    counts[ch] = 1;
  }
  // or more simply with ternary operator
  //   counts[ch] = count ? count + 1 : 1;.
}
console.log(counts);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading