Javascript Toggle item in Array
Today I learned that we can toggle an item in an Array by just calling lodash xor function.
const toggle = (array, item) => _.xor(array, [item])
This way we can add an element to an array if it's not there yet:
toggle([1, 2], 3)
// => [1, 2, 3]
Or delete an element if it's already present:
toggle([1, 2], 2)
// => [1]
Tweet