DevTracePad↗
English ⌄
English简体中文日本語

Field notes / Code companion

Read code through its contract

A useful explanation tells you what changes, what stays shared, and which inputs break the assumptions.

Write the contract before the story

For uniqueById, a helpful contract is “accept an array of non-null objects with IDs; return an array containing the last object for each distinct key.” That is more precise than “remove duplicates.” It makes the choice of identity and the duplicate policy visible. If the caller expects the first object to win, the implementation and requirement disagree even though both produce a unique list.

Follow values, not just lines

The map operation constructs pairs. The Map constructor consumes the pairs. A later pair with the same key replaces the stored value, while iteration order follows the first insertion of each key. The final spread makes a new array. Walk through three items with one duplicate to expose that order/value distinction. A two-item example cannot show every interaction as clearly.

Look for invisible sharing

A new array does not imply new objects. Mutating an object in the output can affect the object referenced by the input. Ask whether consumers need a shallow collection or an independent copy. Also inspect missing IDs and mixed key types: two missing IDs collide at undefined, while 1 and "1" remain different keys. These are behavioral facts to check against requirements, not automatic defects.

Convert explanation into checks

Try empty input, a single object, duplicate IDs, missing IDs, and an invalid item. Record expected output before running anything. If an assistant claims the code sorts items or deeply clones them, locate the operation that would do that; none exists in this snippet. Good explanations remain accountable to the code you can see.

Worked example

Code companion

Authored example — this fixed result only describes the sample input. It is not a live AI response.

Source

function uniqueById(items) {
  return [...new Map(items.map(item => [item.id, item])).values()];
}

Annotated result

PURPOSE
Returns one object per distinct id.

HOW IT WORKS
items.map creates [id, object] pairs. Map keeps one value for each key. A later duplicate replaces the value without moving the key’s original position. The spread creates a new array.

IMPORTANT DETAIL
For [{id:1,v:"a"},{id:2,v:"b"},{id:1,v:"c"}], the expected result is [{id:1,v:"c"},{id:2,v:"b"}]. This is a reasoned example, not an execution log.

LIMITS
Objects are shared with the input, not deeply cloned. Missing IDs collapse under the undefined key. Null items throw. Numeric 1 and string "1" remain distinct keys.