简体   繁体   中英

Using Splice() function, how do I remove specific array elements?

When an image is clicked, my code is supposed to adds the images _id details to the clickedImagesArray array. This it does successfully. However when the image is clicked again, my code fails to remove it from the clickedImagesArray array.

Find below my code:

"click .image": function (event) {

var clickedImage = [this._id];
var clicked = this._id;
var clickedImagesArray = Session.get('clickedImages');

clickedImage.forEach(function (clicked){
    //#### If no duplcate then push() 
    if (clickedImage.indexOf(clicked) ==-1) {
        alert("NOOOO Duplicates!" + clicked);  
        clickedImagesArray.push({imageId: clicked});
        }
    else if (clickedImage.indexOf(clicked) == 0) {
    //#### Else when duplcate found delete duplicate
        alert("Found Duplicates!" + clicked);       
        clickedImagesArray.splice({imageId: clicked});

I have a feeling I am not using the splice() function correctly.

        }     
  }); 

});

Any help would be greatly appreciated.

You need to extract the index in the array that contains your value. and then use splice to remove that record from the index.

splice(startIndex, deleteCount)

startIndex: is the index that you want to start deleting from deleteCount: the number of records that you want to delete, starting from the startIndex

// find the index of the imageId in the array.
var index = clickedImage.indexOf(clicked);

// if item is found in the array remove it.
if (index !== -1) {
  // remove one item starting from the index.
  clickedImage.splice(index, 1);
}

read the documentation in MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

I think that there is a mistake here:

else if (clickedImage.indexOf(clicked) == 0) {

You should change to:

else if (clickedImage.indexOf(clicked) != -1) {

This is because you don´t know the exact index of your element.

Oh, and the splice is wrong too, you need to find the index of the element to remove it, like this:

clickedImagesArray.splice(clickedImage.indexOf(clicked), 1);

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