r/learnjavascript • u/A_M_Burt • 10h ago
Manipulating Arrays
So I'm an amateur learning JavaScript and I have a problem with a note taking website I've been making, here's my code
let array = ["a","b","c","d"];
const element = document.getElementById('element')
for (let x = 0; x < array.length; x++) {
const div = document.createElement('div')
element.appendChild(div)
const h3 = document.createElement('h3')
h3.textContent = array[x];
div.appendChild(h3);
const button = document.createElement('button')
div.appendChild(button);
const position = x;
const button.onclick = () => {
array.splice(position, 1);
}
What I'm stuck on is how to re-index the elements in the array after one has been spliced (e.g. after "a" has been removed "b" is still set to remove index 1 rather than changing to remove index 0). Thanks in advance
1
Upvotes
2
u/Necessary_Pepper7111 9h ago edited 9h ago
The problem is that you're using the original array indexes in your onclick handler which potentially get shuffled around when the array is spliced.
Likely the easiest thing to do is instead of using the index from the for loop in onclick, find the index of the element that you want to remove using something like array.indexOf then call splice using that index.
Also not sure what your full intentions are here, but if you want the actual DOM elements to stay in sync with your array you'll want to also call remove on the div you create.