pixeltooth pixeltooth - 1 year ago 78
jQuery Question

Jquery - Simple Array, pushing item in if its not there already, removing item if it is there

I'm building a simple filtering system, I simply want to add a string to an array and remove it if its already there on click of a link. I'll try to explain the best I can..

//so I start with an empty array
var filters [];
//when a link is clicked I want to add it to the array..
$('li a', context).click(function(e){
//so I get the value held in the data-event attribute of the clicked item example: "john"
newFilter = $(this).attr('data-event');
//this is where I get stuck, I want to test to see if the string I now have
//in 'newFilter' is in the array already or not.. if it is in the array I
//want to remove it, but if it doesnt exist in the array i want to add it..
if(jQuery.inArray(newFilter, filters){
//add to array
} else {
//remove from array

Answer Source

$.inArray() returns the index of the item if it is found, and -1 otherwise (just like indexOf() does, when supported). Therefore, you can write something like:

var found = jQuery.inArray(newFilter, filters);
if (found >= 0) {
    // Element was found, remove it.
    filters.splice(found, 1);
} else {
    // Element was not found, add it.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download