Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

87
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda