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

247
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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