-6

I was wondering how I can add/remove item to array depending on if it's already in there.

Basically, I have a list of items and every item has their own ID, I want to add it or remove it depending on if it's already in the basket array and indicate (with css) if it's already in there.

Thanks in advance.

3
  • 1
    What you have tried so far? Commented Jul 19, 2017 at 13:11
  • 1
    What have you tried? post some code. stackoverflow.com/help/how-to-ask Commented Jul 19, 2017 at 13:12
  • 7
    This is the kind of thing you should really be able to Google. 'How do I add an item to an array', ' How do I check if element exists in array'... Commented Jul 19, 2017 at 13:13

1 Answer 1

0

You can use jQuery built in function $.inArray

cart = ["value1","value2","value3","value4"];  // Cart Items
var new-item = "value2";
var index = $.inArray(new-item, cart);

if(index == -1){
    // Item doesn't exist. Add this item to the cart
    cart.push(new-item);
}else{
    //Item already exists.
    //Delete that item.
    unset($array[index]);
}

console.log(cart); //Display the cart items.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.