How to toggle an element in array using JavaScript? How to toggle an element in array using JavaScript? arrays arrays

How to toggle an element in array using JavaScript?


You could do it without a 3rd party library, this would be more efficient, like this. (this only removes the first instance of a value if found, not multiple)

Javascript

var a = [0, 1, 2, 3, 4, 6, 7, 8, 9],    b = 5,    c = 6;function addOrRemove(array, value) {    var index = array.indexOf(value);    if (index === -1) {        array.push(value);    } else {        array.splice(index, 1);    }}console.log(a);addOrRemove(a, b);console.log(a);addOrRemove(a, c);console.log(a);

Output

[0, 1, 2, 3, 4, 6, 7, 8, 9][0, 1, 2, 3, 4, 6, 7, 8, 9, 5][0, 1, 2, 3, 4, 7, 8, 9, 5] 

On jsfiddle


You can use the lodash function "xor":

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

If you don't have an array as 2nd parameter you can simpy wrap the variable into an array

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

Here's the doc: https://lodash.com/docs/4.16.4#xor


For immutable state ( clone array ):

const addOrRemove = (arr, item) => arr.includes(item) ? arr.filter(i => i !== item) : [ ...arr, item ];