Search code examples
javascriptarraysdrop-duplicates

How not to add duplicate elements in the DOM


I know it is a very easy question but I am still struggling. I created a function which adds element in an Array and after that I am using forEach loop for appending them in the DOM. But I am unable to prevent addition of duplicate elements.

const btn = document.querySelector("button");

btn.addEventListener("click", () => {
  addItem(btn.innerText);
});

function addItem(item) {
  let items = [];

  if (!items.includes(item)) {
    items.push(item);
  }

  items.forEach((element) => {
    const li = Object.assign(document.createElement("li"), {
      innerText: element
    });

    document.body.appendChild(li);
  });
}
@import url("https://cdn.jsdelivr.net/gh/KunalTanwar/organise.css/css/organise.inter.min.css");
body {
  display: grid;
  place-items: center;
}

button {
  border: 0;
  background: none;
  padding: 1rem 2rem;
  box-shadow: inset 0 0 0 1px gray;
}
<button> Add Me </button>

What I have tried so far :

[...new Set(items)].forEach((element) => {
  const li = Object.assign(document.createElement("li"), {
    innerText: element
  });

  document.body.appendChild(li);
});

Another Method -

if (!items.includes(item)) {
  items.push(item);
} else {
  return
}

lastly -

if (!items.includes(item)) {
  items.push(item);
} else {
  items = [...new Set(items)]
}

But still no luck!!


Solution

  • items needs to be declared outside of the function so it has a global scope, currently, you are declaring it to an empty array on each call to the function in the scope of the function, so it can't find any existing items, also you need to return from your function if the value is found in the array, as pointed out in a friendly comment, I also was not accounting for multiple buttons, which I added a fix for this to add event listeners to all buttons.

    const btns = document.querySelectorAll("button");
    let items = [];
    btns.forEach(b => b.addEventListener("click", () => {
         addItem(b.innerText);
    }));
    
    function addItem(item) {
      if (!items.includes(item)) {
         items.push(item);
      } else {
         return;
      }
    
      
      const li = Object.assign(document.createElement("li"), {
         innerText: item
      });
    
      document.body.appendChild(li);
      
    }
    @import url("https://cdn.jsdelivr.net/gh/KunalTanwar/organise.css/css/organise.inter.min.css");
    body {
      display: grid;
      place-items: center;
    }
    
    button {
      border: 0;
      background: none;
      padding: 1rem 2rem;
      box-shadow: inset 0 0 0 1px gray;
    }
    <button>Add Me</button>
    <button>Add Me Again</button>