1

What is the best way to toggle an item in an array using TypeScript.

With toggle I mean:

  • If present, remove the value.
  • If not present, add the value.

Solution with least amount of computational effort preferred.

1 Answer 1

2

Below is a generic typesafe method that "toggles" a value in an array. Note that the method returns a new array, and doesn't mutate the original one.

const toggle = <T extends unknown>(array: Array<T>, value: T) => {
  const newArray = array.filter((x) => x !== value)
  if (newArray.length === array.length) return array.concat(value)
  return newArray
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.