Skip to content

Home

Toggle element in array

Removes an element from an array if it's included in the array, or pushes it to the array if it isn't.

const toggleElement = (arr, val) =>
  arr.includes(val) ? arr.filter(el => el !== val) : [...arr, val];


toggleElement([1, 2, 3], 2); // [1, 3]
toggleElement([1, 2, 3], 4); // [1, 2, 3, 4]

More like this

Start typing a keyphrase to see matching snippets.