Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!