Search code examples
javascriptsplice

Iterate with map() and delete object with splice without index


I can delete an elements with splice but in map cicle index is already known.

if ($(this).hasClass("saveFavoriteMedia")) {
                    saveId = $(this).attr("data-id");
                    listFavoriteMedia.map(function (x) {
                        if (x.id == saveId) {
                            //delete x.id; // Work but not delete totaly elements
                            listFavoriteMedia.splice(index, x.id); //index in already know
                        }
                    });
                }

Solution

  • You can use 2nd parameter of map's callback funciton - index

    listFavoriteMedia.map(function (x,i) { //i is the index
        if (x.id == saveId) {
           listFavoriteMedia.splice(i, 1);  //observe that 1 is given as second parameter of splice to give count of items to be deleted
        }
    });
    

    Or if the id is unique, use findIndex

    var index = listFavoriteMedia.findIndex( s => s.id == saveId );
    listFavoriteMedia.splice(index, 1); 
    

    If your browser doesn't support arrow function, then

    var index = listFavoriteMedia.findIndex( function(s){ return s.id == saveId });
    listFavoriteMedia.splice(index, 1);