Skip to content

toggle

Returns a new array with item removed if present, or appended if absent — the common “toggle a selection” pattern.

By default, presence is checked with SameValueZero equality (like Array.prototype.includes). Pass key to compare by a derived identity instead — useful for toggling objects by id rather than by reference.

Available since v3.0.0

import { toggle } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { toggle } from 'helpers4/array';
toggle<T>(array: readonly T[] | null | undefined, item: T, key?: function): T[]
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe source array. `null`/`undefined` are treated as empty.
itemTThe item to add or remove
keyfunctionOptional function deriving the identity to compare by (optional)

T[] — A new array with item toggled

Common pattern for multi-select UI state — add if absent, remove if present.

toggle([1, 2, 3], 2)
// => [1, 3]
toggle([1, 3], 2)
// => [1, 3, 2]

Pass a key selector to compare by id instead of object reference.

const selected = [{ id: 1 }, { id: 2 }];
toggle(selected, { id: 1 }, (x) => x.id)
// => [{ id: 2 }]

View source on GitHub