Build the @for block's list reconciliation: track keys, moves, swaps, in-place updates and duplicate keys
Problem
Angular 17's @for (item of items; track item.id) block re-renders a list by reusing a view (a piece of DOM plus its context) for every item whose track key survives, moving it if needed, and creating or destroying only what changed. The algorithm behind it is a common "how does Angular do it" question, and the track expression is a common performance question. Build the reconciliation for one @for block.
const repeater = createRepeater({ track: (i, user) => user.id });
repeater.update([asha, ravi, meera]); // { created: 3, destroyed: 0, moved: 0, updated: 0 }
repeater.update([meera, asha, ravi]); // { created: 0, destroyed: 0, moved: 1, updated: 0 }
repeater.update([{ ...meera, online: true }, asha]); // updated: 1, destroyed: 1Ref. UR-1454 · © UIRound · uiround.com/questions/build-the-for-blocks-list-reconciliation-track-keys-moves-swaps-in-place-updates-and-duplicate-keys
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 6
- edge cases
- 4
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Walk both lists from the start and from the end while the keys match: those views stay where they are (only update
$implicitif the object changed). Most real updates (append, prepend, remove one) finish in this phase with no moves.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.