AniUI Academy
hard+350 XPPractice

Update a nested value immutably

Updating nested state immutably by hand produces a pyramid of spread operators, and getting it wrong either mutates state or copies everything, defeating the reference checks that React.memo and useMemo rely on.

Implement updateIn(source, path, updater). path is an array of segments: strings are object keys, numbers are array indices. Walk to the end of the path, call updater with the value found there, and return a new structure in which that position holds the returned value. Copy only the containers along the path: any branch you did not walk into keeps its original reference, so result.untouched === source.untouched. Arrays stay arrays and objects stay objects. If a segment along the path is missing, create the container the *next* segment needs — an array when that segment is a number, a plain object otherwise — and call updater with undefined at the end. An empty path means the whole value: return updater(source). The input is never modified.

What it has to do

  • Treat string segments as object keys and number segments as array indices.
  • Return a new structure with the value at the path replaced by updater's return value.
  • Share references for every branch not on the path.
  • Keep arrays as arrays, and create missing containers based on the next segment's type.
  • Return updater(source) for an empty path, and never mutate the input.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.