user3574766
user3574766

Reputation: 631

Remove a specified value from an array?

I'm setting an array of IDs as "favourites" in localStorage,

var favIndex=$favourites.indexOf($titleId);
if(favIndex==-1){
    $favourites.push($titleId);
    $('#fav').addClass('favourited');
}
else{

    $('#fav').removeClass('favourited');
}

var favouritesJson=JSON.stringify($favourites);
localStorage.setItem('favourites',favouritesJson);
console.log(localStorage.getItem('favourites',favouritesJson));

If the value is not already in the array it will be added, in the else statement I need to remove $titleId from the array, is this possible and if so how?

Upvotes: 1

Views: 53

Answers (3)

justinledouxweb
justinledouxweb

Reputation: 1357

var favoritesIndex = $favourites.indexOf($titleId)

if( favoritesIndex > -1 ) {
    $favourites.splice( favoritesIndex, 1 );
    $('#fav').removeClass('favourited');
}
else{
    $favourites.push($titleId);
    $('#fav').addClass('favourited');
}

Upvotes: 0

Asad
Asad

Reputation: 3160

use this link array.splice method http://www.w3schools.com/jsref/jsref_splice.asp

Upvotes: 0

cl3m
cl3m

Reputation: 2801

Use the splice method that remove n elements from the given index:

if(favIndex==-1){
    $favourites.push($titleId);
    $('#fav').addClass('favourited');
} else {
    $favourites.splice(favIndex, 1);
    $('#fav').removeClass('favourited');
}

Upvotes: 2

Related Questions