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

Count the occurrence of every alphabet from a string in Javascript

I have seen similar questions like this asked before, such as counting characters in a given string. However when it comes to comparing given string to the letters of the alphabet and returning an object with occurences such as:

const letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

const sampleString = "a bee";

const results = {
 a: 1,
 b: 1,
 c: 0,
 d: 0,
 e: 2,
 f: 0,
 ...
}

>Solution :

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

We can use Array.reduce(),
to count letters in the sampleString.

We start by creating a letterMap to specify all valid letters to be counted.

In the reduce loop, we only increment letters that are present in the letterMap, using the (c in acc) expression.

const letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

const sampleString = "a bee";

const letterMap = letters.reduce((acc, c) => { 
    acc[c] = 0; 
    return acc; 
}, {});

const result = [...sampleString].reduce((acc, c) => {
    if (c in acc) acc[c]++;
    return acc;
}, letterMap);

console.log('Result:', result)
 
.as-console-wrapper { max-height: 100% !important; top: 0; }
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