Removes an element from an array if it's included in the array, or pushes it to the array if it isn't.
Array.prototype.includes()
to check if the given element is in the array.Array.prototype.filter()
to remove the element if it's in the array....
) to push the element if it's not in the array.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]
Would you like to help us improve 30 seconds of code?Take a quick survey
JavaScript, Array
Removes elements from the end of an array until the passed function returns true
.
Returns the removed elements.
JavaScript, Array
Removes elements from the end of an array until the passed function returns false
.
Returns the removed elements.
JavaScript, Array
Mutates the original array to filter out the values at the specified indexes. Returns the removed elements.