1

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?

user3574766
  • 521
  • 2
  • 8
  • 23
  • 1
    Possible duplicate of [Remove a particular element from an array in JavaScript?](http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript) – Thriggle Mar 14 '16 at 19:31

3 Answers3

2

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');
}
cl3m
  • 2,741
  • 16
  • 21
0

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

Asad
  • 2,264
  • 4
  • 17
  • 45
0
var favoritesIndex = $favourites.indexOf($titleId)

if( favoritesIndex > -1 ) {
    $favourites.splice( favoritesIndex, 1 );
    $('#fav').removeClass('favourited');
}
else{
    $favourites.push($titleId);
    $('#fav').addClass('favourited');
}
justinledouxweb
  • 1,139
  • 2
  • 11
  • 26
  • Please explain how your answer solves the problem, don't just post code and expect people to understand. Thanks! – Aziz Mar 14 '16 at 20:48