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

245
Vistas
How to count similar words in a string and display their individual count in a new string?

I am trying to create a function that takes in a string as an input. This function should count each word and display a count number next to the individual word. The count should increase per iteration of the word.

Where the input is string == "this is this sample" and the expected output is "this(2) is(1) this(2) sample(1)"

This is what I have so far:

function wordCounter(string) {
  const array = string.split(" ");
  let count = 0;
  for (let i = 0; i < array.length; i++) {
    // if statement? //
  }
}

From what I understand the string will need to be converted to an array to be looped over. However, I am having difficulty understanding how each specific word can have its own counter. I've also looked into .reduce(), but am having a hard time implementing it.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

My first raw idea would be to do something like this:

function wordCounter(string) {
  const array = string.split(" ");
  let count = {};
  let result = '';
  for (let i = 0; i < array.length; i++) {
    if(count[array[i]]) {
      count[array[i]]+=1;
    } else {
      count[array[i]] = 1;
    }
  }
  Object.keys(count).map(key => {
  result += key + '('+ count[key]+') '; 
  });
  return result;
}
console.log(wordCounter('hello this is a test'));

about 4 years ago · Juan Pablo Isaza Denunciar

0

This seems to work, but be aware it's coded with the intent of not counting blank spaces and includes punctuation/case when considering word count.

function wordCounter(string) {
            var array = string.split(" ");
            //"dictionary" is an object.  We'll store words in it like properties.
            var dictionary = {};
            var final = "";
            var current;
            var currentCount;
            for (let index = 0; index < array.length; index++) {
                current = array[index];
                //If the current array item isn't a blank...
                if (current != "") {
                    //If the word isn't already in dictionary...
                    if (dictionary[current] == null) {
                        //We add it and set it to 1.
                        currentCount = 1;
                        dictionary[current] = currentCount;
                    }
                    //Otherwise...
                    else {
                        //We get the current value, add 1, and set the property to the new value.
                        currentCount = dictionary[current] + 1;
                        dictionary[current] = currentCount;
                    }
                    //Now we append the word, parentheses, and current count.
                    final += current + "(" + currentCount + ") ";
                }
            }
            //Once the loops is done, if our word is greater than 0 characters, we slice the last one (the extra space from our last iteration).
            if (final.length > 0) {
                final = final.slice(0, -1);
            }
            //Print the final text.
            alert(final);
        }
        window.addEventListener('load', function() {
            wordCounter("This right here is this the sample of the sample you wanted.  It's not the same as your sample, but it's a sample none the less.");
            wordCounter("");
            wordCounter("     ");
            wordCounter("    this     this    and    this   ");
        });

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