Counting case sensitive letters

Hi Gliders
I’m having problems with a JS, could you please help me?

function countIdenticalLetters(str) {
    const letterCounts = {};
    for (const letter of str) {
       if (/[a-zA-Z]/.test(letter)) {
            letterCounts[letter] = (letterCounts[letter] || 0) + 1;
        }
    }

    return letterCounts;
}
const input = "Hello, World!";
const result = countIdenticalLetters(input);
result;

Thank’s
Alex

what are you trying to make here?
are you trying to count how many identical letters? What would the output look like?

Hi micheal,
yes correct.
H:1, e:1, l:3,…

hmmm okay let me seee

Alright, try this code

function countLetters() {
  let result = "";

  let inputText = p1.toLowerCase();

  // Loop through letters 'a' to 'z'
  for (let i = 97; i <= 122; i++) {
    let letter = String.fromCharCode(i);
    let count = 0;

    // Count occurrences of the current letter
    for (let j = 0; j < inputText.length; j++) {
      if (inputText[j] === letter) {
        count++;
      }
    }

    // Append the letter and its count to the result if it exists
    if (count > 0) {
      result += letter + ": " + count + ", ";
    }
  }

  // Remove trailing comma and space
  return result.slice(0, -2);
}

return countLetters();

Hi Micheal,
it is counting but it shouldn’t be toLowerCase
and also I have a problem with ä,ö,ü & ß from the german Keyboardlayout & punctuation marks like & and %…

Thank’s
Alex

Alright try this

function countCharacters() {
  let result = "";

  let inputText = p1; // Keep original case for case sensitivity

  // Initialize an object to hold character counts
  let charCount = {};

  // Loop through each character in the string
  for (let i = 0; i < inputText.length; i++) {
    let char = inputText[i];

    // Skip spaces if you don't want them counted
    if (char === " ") {
      continue;
    }

    // Increment the character count in the object
    if (charCount[char]) {
      charCount[char]++;
    } else {
      charCount[char] = 1;
    }
  }

  // Construct the result string
  for (let char in charCount) {
    result += char + ": " + charCount[char] + ", ";
  }

  // Remove trailing comma and space
  return result.slice(0, -2);
}

return countCharacters();

1 Like

It’s working
Thank you!

1 Like

Awesome happy to help

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.