Search code examples
javascriptarrayssplice

Javascript splice removes wrong element


I am somewhat bamboozled over this very simply code not working correcly:

 //find the index to be removed
 cardData.likeData.likeUids.forEach ((entry, index) => {
    if (entry === uid){
      uidFound = true
      uidIndex = index
      console.log ("Found uid, index is " + uidIndex)
      //console shows correct index
    }
  })
  let newLikeUids = cardData.likeData.likeUids.splice (uidIndex, 1)
  //instead of deleting the found index, the element before the index is removed... for some reason

Any idea why this is not working?


Solution

  • I have noticed the problem is you probably using the splice in the wrong way.

    The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice()

    But in your code, you are trying to assign the value of splice to a value which will not working.

    You probably mix the slice and splice. I think in this situation, you should use slice instead.

    The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.