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

88
Visualizações
JavaScript function to get the number of occurrences of each letter in specified string

I am new to JavaScript. Can anyone tell me why counter = 1 is added in following code ?

function count(string) {
  let string1 = string.split("").sort().join("");
  let counter = 1;
  for (let i = 0; i < string1.length; i++) {
    if (string1[i] == string1[i + 1]) {
      counter++;
    } else {
      console.log(string1[i] + " " + counter);
      counter = 1;//-----------> this one
    }
  }
}
count("amanpreetsaingh");
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You sort the whole characters in the string and start from left to right.

If your string is amanpreetsaingh, it becomes aaaeeghimnnprts.

Now what you do is keep a counter=1 starting from index 0. And check for every letter you check if it is equal to the next one, if yes then we are counting for the same letter and increase counter (like in case of the first two as). Once we reach the last a, our next letter (e) is not the same as our current letter, so we log our current value and reset count.

about 4 years ago · Juan Pablo Isaza Relatório

0

you can simply use reduce function:

reduce it's an array method so make sure to transform your string into array by using split(""):

text.split("") // ["a", "a", "a", "a", "b", "b", "b", "c", "c", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d", "d", "d"]

then apply reduce on the result array :

  text.split("").reduce((acc, c) => {
  const counter = acc[c] || 0;
  return {
    ...acc,
    [c]: counter + 1,
  };
}, {}); // { a: 4, b: 3, c: 6, d: 5 }

I suggest you watch this series of videos about the arrays method from ack Herrington: https://youtu.be/NaJI7RkSPx8

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