JQuery - простой массив, нажав элемент, если его там нет, удалив элемент, если он есть

Я создаю простую систему фильтрации, я просто хочу добавить строку в массив и удалить ее, если она уже есть при щелчке ссылки. Я попытаюсь объяснить лучшее, что могу.

$(document).ready(function(){
    //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
        };
    e.preventDefault();
    });
});

Ответы

Ответ 1

$. inArray() возвращает индекс элемента, если он найден, и -1 в противном случае (точно так же, как indexOf(), когда поддерживается). Поэтому вы можете написать что-то вроде:

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.
    filters.push(newFilter);
}

Ответ 2

Я мог ошибаться, но я считаю, что это так же просто, как использование базового javascript: [.push, .splice]

if($.inArray(newFilter, filters)<0) {
    //add to array
    filters.push(newFilter); // <- basic JS see Array.push
} 
else {
    //remove from array
    filters.splice($.inArray(newFilter, filters),1); // <- basic JS see Array.splice
};

Конечно, если вы действительно хотите его упростить, вы можете удалить некоторые строки и свести их к встроенному кодированию.

0 > $.inArray(newFilter,filters) ? filters.push(newFilter) : filters.splice($.inArray(newFilter,filters),1);

Для ABSOLUTE pure JS:

var i; (i=filters.indexOf(newFilter))<0?filters.push(newFilter):filters.splice(i,1);

Разбито:

var i;  //  Basic variable to be used if index of item exist
//  The following is simply an opening to an inline if statement.
//  It wrapped in () because we want `i` to equal the index of the item, if found, not what to follow the `?`.
//  So this says "If i = an index value less than 0".
(i=filters.indexOf(newFilter)) < 0 ?
    //  If it was not found, the index will be -1, thus push new item onto array
    filters.push(newFilter) : 
        //  If found, i will be the index of the item found, so we can now use it to simply splice that item from the array.
        filters.splice(i,1);

Ответ 3

Если у вас нет конкретной причины использовать массивы, я бы предложил вместо этого использовать объект.

$(document).ready(function(){
    //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 (filters.hasOwnProperty(newFilter)) {
           // remove from object
           delete filters[newFilter];
        } else {
           //add to object
           filters[newFilter] = 'FOO'; // some sentinel since we don't care about value 
        };
    e.preventDefault();
    });
});

Ответ 4

Вы можете использовать функцию lodash "xor":

_.xor([2, 1], [2, 3]);
// => [1, 3]

Если у вас нет массива в качестве второго параметра, вы можете просто переносить переменную в массив

var variableToInsertOrRemove = 2;
_.xor([2, 1], [variableToInsertOrRemove]);
// => [1]
_.xor([1, 3], [variableToInsertOrRemove]);
// => [1, 2, 3]

Здесь doc: https://lodash.com/docs/4.16.4#xor

Ответ 5

Другой способ, который я нашел:

Удалить

filters = jQuery.grep(filters, function(value) {
  return value != newFilter;
});

добавить:

filters.push(newFilter)

Ответ 6

Что-то вроде этого?

var filters = [];
// ...
var newFilter = '...';
if(-1 !== (idx = jQuery.inArray(newFilter, filters))) {
   // remove
   filters.splice(idx, 1);
} else {
   // add
   filters.push(newFilter);
}