Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Toggle Membership

Immutable Arraysmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 111: The Spread Operator (...)

Implement `toggleInArray(list, value)` returning a new array with `value` removed if present, or added if absent (useful for multi-select state).

Sample tests

Input: toggleInArray([1,2,3], 2)
Output: [1,3]
Input: toggleInArray([1,3], 2)
Output: [1,3,2]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating with push or splice instead of returning a new array.
  • Adding a duplicate when the value is already present.

Learning resources

  • React: Updating Arrays in State
Approach & explanation (try first)

This is the pattern behind toggling a checkbox in a set of selected ids. If the value is already in the array you remove it with filter; otherwise you add it with spread. Either branch returns a new array.

Loading...
⌘/Ctrl + Enter

Run your code to see results.