Toggle values into and out of an array in Javascript
my ES* variant
const toggleArrayValue = (arrayList, arrayValue) =>
arrayList.includes(arrayValue)
? arrayList.filter(el => el !== arrayValue)
: [...arrayList, arrayValue]
extremely compact lodash version, using xor function, which is used to create a new array of values found only in one array and not the other
xor(array, [valueYouWantToToggle])
Assuming the order of the items doesn't matter you can do something like this:
function toggleArrayItem(a, v) {
var i = a.indexOf(v);
if (i === -1)
a.push(v);
else
a.splice(i,1);
}
The .indexOf()
method does work in IE from version 9 onwards, but if you need to support older IE versions you can use a shim as explained at MDN. Or if you're using jQuery anyway use $.inArray()
instead.