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

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

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 Denunciar

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