Home > other >  Deleting the elements of the copy array one by one with a button and adding the deleted element to a
Deleting the elements of the copy array one by one with a button and adding the deleted element to a

Time:12-19

I write an app in which a dot appears when you click on a certain place. I store the positions of the dots in an array. I have a button that restores the previous dot when clicked and at the same time adds this element to another array. And here's the problem. On click on this button I create a copy of this main array and remove the previous item from it, but when I have multiple dots and want to delete it always returns me the last one I added.

Here's a code:

const pointsData = []
const redoPoints = []

container.addEventListener('click', (e) => {
   const positionX = e.clientX
   const positionY = e.clientY
   pointsData.push({ positionX, positionY })
   showList(pointsData)
})

const showList = (pointsArr) => {
   container.innerHTML = ""
   pointsArr.forEach(point => {
      container.innerHTML  = `<div  style="left: ${point.positionX}px; top: ${point.positionY}px"></div>`
   })
}

undoButton.addEventListener('click', () => {
   if (pointsData.length > 0) {
      const newPoints = [...pointsData]
      const popped = newPoints.pop()
      redoPoints.push(popped)
      const newPoints = [...newPoints, popped]
      showList(newPoints)
   }
})

For example, I have array like this: [{x:23, y:43},{x:432,y:33},{x:34, y:354}] and when I click the undo button it always returns me x:34,y:354 I think I explained well :D PS. Sorry for my english!

CodePudding user response:

In the 'undoButton' event listener, adding the 'popped' point to 'newPoints' again seems not right (above the showList call). In the end nothing changes if the same point is being popped and added. Consider working with 'pointsData' without using the 'newPoints' array.

If you are trying to remove a point and save it to redoPoints you may try this code:

undoButton.addEventListener('click', () => {
   if (pointsData.length > 0) {
      const popped = pointsData.pop()
      redoPoints.push(popped)      
      showList(pointsData)
   }
})

  • Related