Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
How can I find out how many of each letter is in a given string?

So I want my code to count the amount of times a letter shows up within a string and output the result.

ie:

amount(door, o) ===> 2

Can I do it using a for loop using

function(amount,letter){
  var  count=0
  for (var i=0 ; i < amount.length ; i++) {
    if(amount[i] == letter[i]) count++
    }
  }

not really sure how to make it work

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your code was almost correct but there some mistakes

  • You have to give the function a name
  • You have to return count
  • You have to pass actual strings
  • You should use let or const instead of var
  • You should use === instead of ==

function amount(word, letter) {
  let count = 0;
  for (let i = 0; i < word.length; i++) {
    if(word[i] === letter) count++
  }
  return count;
}

console.log(amount('door', 'o'));

Using array methods you can simplify even more

function amount(word, letter) {
  return Array.prototype.reduce.call(word, (acc, el) => acc + (el === letter), 0);
}

console.log(amount('door', 'o'));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can split the string into an array, then loop through each of the letters. We have a letterTracker object, which is where our values are stored. If the key of the letter doesn't exist in the object already, we'll add the key to it. If it does exist, we'll just add one to it.

var countLetters = (string)=>{
    const stringArr = string.split('')
    let letterTracker = {};
    stringArr.forEach(letter=>{
        letterTracker[letter]
            ? letterTracker[letter]++
            : letterTracker[letter] = 1
    });
    return letterTracker;
}

countLetters('wuddup'); //returns { w: 1, u: 2, d: 2, p: 1 }

Using a more ES5 friendly method, and without splitting the string into an array, we can do this (the same result will be achieved):

function countLetters(string){
    let letterTracker = {};
    for(let i = 0; i < string.length; i++){
        if(letterTracker[string[i]]){
            letterTracker[string[i]]++
        } else {
            letterTracker[string[i]] = 1
        }
    }
    return letterTracker;
}

countLetters('wuddupp?'); //returns { w: 1, u: 2, d: 2, p: 2, ?: 1 }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda