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.
Code
// 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
Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.