2012-03-07 23 views
15

Estoy construyendo un sistema de filtrado simple, simplemente quiero agregar una cadena a una matriz y eliminarla si ya está allí en clic de un enlace Voy a tratar de explicar lo mejor que pueda ..Jquery: matriz simple, empujando el elemento si ya no está allí, eliminando el elemento si está allí

$(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(); 
    }); 
}); 
+3

¿Puedes probar 'indexof' tu cadena contra la matriz? si devuelve -1, 'push', si es mayor que -1,' pop' – MilkyWayJoe

Respuesta

41

$.inArray() devuelve el índice del elemento, si se comprueba, y -1 lo contrario (al igual indexOf(), cuando es compatible). Por lo tanto, se puede escribir algo como:

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); 
} 
6

Podría estar equivocado, pero creo que esto es tan simple como el uso de JavaScript básico: [.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 
}; 

Por supuesto si realmente quiere simplificarlo, podría eliminar algunas líneas y reducirla a la codificación en línea.

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

Para JS puros ABSOLUTOS:

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

Analizado:

var i; // Basic variable to be used if index of item exist 
// The following is simply an opening to an inline if statement. 
// It's wrapped in() because we want `i` to equal the index of the item, if found, not what's 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); 
+4

'$ .inArray()' es una función jQuery. Eso no es "JavaScript básico" ... – aendrew

+0

@aendrew Me refería a wuts iinside el método – SpYk3HH

0

Otra manera que he encontrado:

Quitar:

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

complemento:

filters.push(newFilter) 
1

A menos que tenga una razón específica para el uso de matrices, sugeriría usar un objeto en su lugar.

$(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(); 
    }); 
}); 
+0

Hola jbabey .. ¿Alguna pregunta de novato sobre cómo ver los contenidos en el objeto usando console.log? Actualmente obtengo - [Object Object] – Iamsamstimpson

+1

console.log (myObject.propName) o console.log (myObject ['propName']) – jbabey

0

Algo así como thats?

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

Puede utilizar la función lodash "XOR":

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

Si usted no tiene una matriz como segundo parámetro se puede envolver simpy la variable en una matriz

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

Aquí está el documento: https://lodash.com/docs/4.16.4#xor

Cuestiones relacionadas