Martin Devillers
Martin Devillers

Reputation: 17992

TypeScript: add to array if not present, or remove if present

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

With toggle I mean:

Solution with least amount of computational effort preferred.

Upvotes: 1

Views: 640

Answers (1)

Martin Devillers
Martin Devillers

Reputation: 17992

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
}

Upvotes: 2

Related Questions