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

253
Visualizações
Using ForEach and getting repeated elements in JavaScript

What I am trying to do is with an input add words into an array, then as you add the words I want them to be displayed in a list. So I did a function to render the list, and used a for each, then used that function inside the function that push the words into the array. The thing is that when you add the words the for each executes and duplicates all the words.

if you add tree as a word you get the output: tree

if you add rabbit you get the output : tree, tree, rabbit

lets say you want to add falcon and you get: tree, tree, rabbit, tree, tree, rabbit, falcon

Here is the code


const renderPass = function (array, location) {
  array.forEach((element) => {
       let html = `<li class="k">${element}</li>`;

       location.insertAdjacentHTML("afterbegin", html);
  });
};


const savingKeyWords = function (e) {
   e.preventDefault();

   keyWords.push(keyWord.value);
   renderPass(keyWords, listOfKeys);

   console.log(keyWords);

   clear(keyWord);
};

could you help me with this??

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

0

That is because you seem to be using the same array defined in the global context over and over on every invocation. Just create a new array when ever saving keywords is invoked.

const savingKeyWords = function (e) {
   let keyWords = [];

   e.preventDefault();

   keyWords.push(keyWord.value);
   renderPass(keyWords, listOfKeys);

   console.log(keyWords);

   clear(keyWord);
};
about 4 years ago · Juan Pablo Isaza Relatório

0

I think 'keyWords' has to be replaced with 'keyWord.value' in here:

renderPass(keyWords, listOfKeys);

And

const renderPass = function (keyWord, location) {
       let html = `<li class="k">${keyWord}</li>`;
       location.insertAdjacentHTML("afterbegin", html);
};

I hope this will be helpful for you. Thanks

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