Home > Mobile >  Using ForEach and getting repeated elements in JavaScript
Using ForEach and getting repeated elements in JavaScript

Time:06-11

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 >${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??

CodePudding user response:

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);
};

CodePudding user response:

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

renderPass(keyWords, listOfKeys);

And

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

I hope this will be helpful for you. Thanks

  • Related