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
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
array | readonly T[] | null | undefined | The source array. `null`/`undefined` are treated as empty. |
item | T | The item to add or remove |
key | function | Optional function deriving the identity to compare by (optional) |
Returns
Section titled “Returns”T[] — A new array with item toggled
Examples
Section titled “Examples”Toggle a selection
Section titled “Toggle a selection”Common pattern for multi-select UI state — add if absent, remove if present.
Toggle objects by a derived key
Section titled “Toggle objects by a derived key”Pass a key selector to compare by id instead of object reference.
