Today I Learned

A Hashrocket project

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]
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.