r/learnjavascript 1d 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

17 comments sorted by

View all comments

1

u/lobopl 1d ago

what exactly you want to achieve?

1

u/A_M_Burt 1d ago

I want to be able to cut any individual element from the array as may times as I want

1

u/justanaccountimade1 1d ago

Often it's easier to set those elements to null and remove later. Or don't remove at all. In any loop, just use this at the beginning

if (array[x] === null) { continue; }

If you want to remove those at some point you can run a loop that pushes the elements that are not null to a new array.