简体   繁体   中英

Removing specific item from an array

I am using the following function to save items into an array in local storage. Once an item has been stored I want to remove it from the array by selecting the save button again. Currently users can save the same item multiple times. By modifying the save button to remove the item users will have an easy way of removing items and it will prevent them from saving the same item multiple times.

$('.saveButton').click(function(){
    var film = JSON.parse(sessionStorage.getItem("film"));
    var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");
    saveFilm.push(film);
    localStorage.setItem("save", JSON.stringify(saveFilm));    
});

How should I build on the function to allow me to do this?

edit:

$('.saveButton').click(function(){
    var film = JSON.parse(sessionStorage.getItem("film"));
    var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");
    var arrayLength = (saveFilm.length);
    $.each(saveFilm, function(index,saveFilm){
        if(saveFilm.id===film.id){
            saveFilm.splice(saveFilm.indexOf(film), 1);
            console.log("true")
        }
        else{
            saveFilm.push(film);
            console.log("false")
        }
    localStorage.setItem("save", JSON.stringify(saveFilm));
    })
});

edit2:

$('.saveButton').click(function(){
var film = JSON.parse(sessionStorage.getItem("film"));
var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");
var arrayLength = (saveFilm.length);
if (arrayLength>0){
    for(i=0; i<arrayLength; i++){
        if(saveFilm[i].id===film.id){
            saveFilm.splice(saveFilm.id, 1);
        }
        else{
            saveFilm.push(film);     
        }
    }
    }else{
        saveFilm.push(film);


     }
        localStorage.setItem("save", JSON.stringify(saveFilm));
});

Basically, you'll just read the value back, JSON.parse() it, remove the element, then save it again.

If you're just adding it to the function above, just add something like this:

$('.saveButton').click(function(){
    var film = JSON.parse(sessionStorage.getItem("film"));
    var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");

    if (!saveFilm.includes(film)) {
      saveFilm.push(film);
    } else {
      saveFilm.splice(saveFilm.indexOf(film), 1);
    }

    localStorage.setItem("save", JSON.stringify(saveFilm));    
});

If film is an object though, this won't work. Instead, you'll need to have some kind of key you can use to find the element (such as name) which you'll instead loop through the array and find. Once you find it (or don't find it), then the logic I shared will work again.

// assuming film.name is a valid unique identifier 
function getFilmIndex(films, film) {
   const film = films.find(f => f.name === film.name);
   return film ? null : films.indexOf(film);
}

You have to be careful when splicing from front to end. When splicing and iterating automatically (using for loop as (var i = 0; i < arr.length; i++)) what ends up happening is if you have duplicates back-to-back then you will skip the duplicate.

 var arr = [1, 2, 2, 3, 4], toRemove = 2; for(var i = 0; i < arr.length; i++){ if(arr[i] === toRemove) arr.splice(i, 1); } console.log(arr); 

What happens is you get rid of the first 2, move the second where that 2 was but starting looking at 3. There are 2 ways prevents this:

1. Manually iterate i when you do not splice an element

 var arr = [1, 2, 2, 3, 4], toRemove = 2; for(var i = 0; i < arr.length;){ if(arr[i] === toRemove){ arr.splice(i, 1); }else{ i++; } } console.log(arr); 

2. Itererate in reverse order (preferred way)

 var arr = [1, 2, 2, 3, 4], toRemove = 2; for(var i = arr.length - 1; i > 0; i--){ if(arr[i] === toRemove) arr.splice(i, 1); } console.log(arr); 

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