-1

i wanna delete onclick the item in localstorage but the algo delete always the first element not the item clicked on in the html view

var array = [...deleteButton]

array.forEach((item, index) => 
{
    var id = item.parentElement.parentElement.parentElement.dataset.id
    item.addEventListener("click", () => 
    {
        cart.forEach(elem =>
        {
            if(id === elem[0])
            {
                console.log(cart);
                cart.splice(elem, 1);
                location.reload();
                console.log(cart);
                localStorage.setItem("cart", JSON.stringify(cart))
                console.log(index, elem[0]);
                console.log(cart);
            }
        });
    })
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
curlynux
  • 1
  • 3

1 Answers1

1

The argument to splice() has to be the index. Use findIndex() to get the index of the element with the matching value, and use that to splice.

array.forEach((item, index) => {
  var id = item.parentElement.parentElement.parentElement.dataset.id
  item.addEventListener("click", () => {
    let cartIndex = cart.findIndex(elem => id == elem[0]);
    if (cartIndex) {
      cart.splice(cartIndex, 1);
      localStorage.setItem("cart", JSON.stringify(cart));
      location.reload();
    }
  });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • i already found the solution by myself by replacing the `elem` in `cart.splice` by `index` but thank you for yours it also worked fine ! – curlynux Jul 27 '22 at 11:34
  • You shouldn't splice an array while looping over it. See https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop – Barmar Jul 27 '22 at 14:14
  • i have another problem to solve if you can help me on it, – curlynux Jul 27 '22 at 16:30
  • Post another question. If I see it and I'm interested in answering, I will. – Barmar Jul 27 '22 at 16:36