0

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

6 Answers6

2

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; }

Here's another way, using just one loop, again using Array.reduce(), this assumes we don't wish to count whitespace:

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 result = [...letters, ...sampleString].reduce((acc, c) => {
    if (c in acc) { 
        acc[c]++;
    } else if (c.trim()) {
        acc[c] = 0;
    }
    return acc;
}, {});

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Terry Lennox
  • 24,896
  • 3
  • 23
  • 34
1

I like using Object.fromEntries for this:

const sampleString = "a bee";
const result = Object.fromEntries(Array.from("abcdefghijklmnopqrstuvwxyz", ch => [ch, 0]));
for (let ch of sampleString) 
    if (ch in result) result[ch]++;
console.log(result);
trincot
  • 263,463
  • 30
  • 215
  • 251
  • if you `Object.seal(result)` before iterating over `sampleString`, it doesn't try to add characters that are not part of the alphabet. – Thomas Dec 08 '21 at 12:54
0

Using Array.reduce and String.match may be an idea. So, for each letter of letters, use match (length) to determine the frequency of the letter in the given sample.

const letters = `abcdefghijklmnopqrstuvwxyz`.split(``);
const freq = (chr, sample) => (sample.match(RegExp(chr, `g`)) || []).length;
const result = letters.reduce( (acc, chr) => 
  ({...acc, [chr]: freq(chr, acc.sample)}), {sample: "a bee"});
console.log(result);
KooiInc
  • 112,400
  • 31
  • 139
  • 174
0

Or a more undestandable way

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";
results = {};
sampleString.forEach(letter=>{
   if(letters.includes(letter)) {
      if(results[letter] === undefined) results[letter]=0;
      results[letter]++;
   }
});
Soroush Bgm
  • 522
  • 1
  • 13
0

making the value as a key is a bad practice, because it will be hard to read, I recommend to call it what it is:

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 tempString = "This is a string.";
let results = []
letters.forEach( char =>{
  const count = countCharacterOccurences(tempString, char)
  results.push({ alphabet: char, count })
})

function countCharacterOccurences(string, char) {
   return string.split(char).length - 1;
}

console.log(results)

//filter alphabet with value
const alphabetWithCount = results.filter( result => {
   return result.count > 0
})
console.log(alphabetWithCount)

//log alphabet only with counts
const alphabetOnlyWithCounts = alphabetWithCounts.map( alphabetWithCount => {
    return alphabetWithCount.alphabet
})

console.log(alphabetOnlyWithCounts)

//
JCue
  • 81
  • 7
0

You can apply .reduce() on the letters directly and in each iteration use RegExp() to replace all letters that do not match the current letter and the count the remaining letters in the string, if any, with .length:

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 = letters.reduce((result,letter) => ({
    ...result, 
    [letter]: sampleString.replace(new RegExp(`[^${letter}]`,'g'), "").length
}), {});

console.log( results );

NOTE:

Please note that:

sr.replace(new RegExp('[^a]','g'), "").length

for example, is equivalent to:

sr.replace(/[^a]/g,"").length

See: JavaScript: How many times a character occurs in a string?

PeterKA
  • 22,910
  • 4
  • 23
  • 48