Array Diff Reports Added And Removed Items

Diffing two snapshots with Sets answers which items arrived and which left, so change feeds and cache invalidation can react to exact deltas.

JavascriptData Integrity

Code

javascriptsnippet
25 lines
// Compare two snapshots of a list: which items arrived, which left.
function diff(previous, current) {
  const before = new Set(previous);
  const after = new Set(current);
  return {
    added: current.filter((item) => !before.has(item)),
    removed: previous.filter((item) => !after.has(item)),
  };
}

const yesterday = ['orders.js', 'auth.js', 'utils.js', 'legacy.js'];
const today = ['orders.js', 'auth.js', 'billing.js', 'utils.js', 'tests.js'];

const { added, removed } = diff(yesterday, today);
console.log('added:  ', added);
console.log('removed:', removed);

// Items present in both snapshots stay out of both results.
const overlap = diff(['a', 'b', 'c'], ['b', 'c']);
console.log('overlap -> added:', overlap.added, '| removed:', overlap.removed);

// Duplicate entries inside one snapshot do not leak into the diff,
// because each side filters against the other snapshot's Set.
const duplicated = diff(['x', 'x', 'y'], ['x']);
console.log('dupes   -> added:', duplicated.added, '| removed:', duplicated.removed);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

added:   [ 'billing.js', 'tests.js' ]
removed: [ 'legacy.js' ]
overlap -> added: [] | removed: [ 'a' ]
dupes   -> added: [] | removed: [ 'y' ]

How it works

Count the function diff as the entire surface area of Array Diff Reports Added And Removed Items.

It builds and returns a fresh value rather than reusing its inputs.

Points of care

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Using it

The main signature reads function diff(previous, current)

The run emits 4 labeled sections — added:, removed:, overlap -> added:, dupes -> added: — one per step.

Key statements

const before = new Set(previous);
const after = new Set(current);

Interactive Tools for This Topic

FAQ

Does `diff` modify its input?
No mutation happens — the function reads its input and returns a new value.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `diff` at load time.