简体   繁体   中英

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?

You should use findIndex . I don't know how your array looks like but in a similar case where you want to remove the first 1 from an array of 1 and 0, you'd write something like this:

 const arr = [0,0,0,0,0,1,0,0,0]; arr.splice(arr.findIndex(e => e === 1), 1); console.log(arr);

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.

Maybe filter method of Array can help you

cardData.likeData.likeUids.filter ((entry) => {
    return entry !== uid;
});

If you have many uids to remove

you could try

cardData.likeData.likeUids.filter ((entry) => {
    return uids.indexOf(entry) === -1;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

I made a small bit of code from what you have written, seems to do what you want:

Changing the UID will decide what is removed from the data.

let data = [1,2,3];

let uid = 1;
let foundUidIndex;

data.forEach ((entry, index) => {
    if (entry === uid){
      foundUidIndex = index;
      console.log ("Found uid, index is " + foundUidIndex)
    }
  })
 data.splice(foundUidIndex, 1);
  
console.log(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM