Search code examples
javascriptarraysmeteorsplice

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.


Solution

  • 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