JavaScriptEasy
Union of two arrays
The union is every distinct value that appears in either array: [...new Set([...a, ...b])] does it in O(n + m) time and keeps first-occurrence order; for objects, merge by a key using a Map.
Variations
- Primitives:
new Set([...a, ...b]). RememberSettreatsNaNas equal toNaNand0as equal to-0. - Objects by key: a
Mapfrom key to object. Decide whether the first or the last occurrence wins (later sources often hold fresher data). - Merging records: when the same id appears in both, merge their fields (
{ ...a, ...b }). - Sorted arrays: two pointers produce a sorted, de-duplicated union in O(n + m).
- Many arrays:
new Set(arrays.flat()). - Multiset union: keep the maximum count of each value from either array.
Built-in Set methods (ES2025)
setA.union(setB) returns a new Set; also intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf, isDisjointFrom. Feature-detect for older environments.
Related operations
- Difference (in A but not B):
a.filter(x => !setB.has(x)). - Symmetric difference (in exactly one): difference both ways, combined.
Code example
js
1const a = [1, 2, 3, NaN];2const b = [3, 4, 5, NaN];3console.log([...new Set([...a, ...b])]); // [1, 2, 3, NaN, 4, 5]45// Objects by key: later sources win, fields merged6function unionBy(key, ...lists) {7 const map = new Map();8 for (const item of lists.flat()) map.set(item[key], { ...map.get(item[key]), ...item });9 return [...map.values()];10}11const cached = [{ id: 1, name: "Ada" }, { id: 2, name: "Linus" }];12const fresh = [{ id: 2, name: "Linus T.", online: true }, { id: 3, name: "Grace" }];13console.log(unionBy("id", cached, fresh));14// [{ id: 1, name: "Ada" }, { id: 2, name: "Linus T.", online: true }, { id: 3, name: "Grace" }]1516// Sorted union with two pointers17function unionSorted(x, y) {18 const out = [];19 let i = 0, j = 0;20 const push = (v) => out.at(-1) !== v && out.push(v);21 while (i < x.length && j < y.length) {22 if (x[i] < y[j]) push(x[i++]);23 else if (x[i] > y[j]) push(y[j++]);24 else { push(x[i]); i++; j++; }25 }26 while (i < x.length) push(x[i++]);27 while (j < y.length) push(y[j++]);28 return out;29}30console.log(unionSorted([1, 3, 5, 5], [2, 3, 6])); // [1, 2, 3, 5, 6]3132// Difference and symmetric difference33const setB = new Set(b);34const setA = new Set(a);35console.log(a.filter((x) => !setB.has(x)), [...a.filter((x) => !setB.has(x)), ...b.filter((x) => !setA.has(x))]); // [1, 2] [1, 2, 4, 5]3637if (typeof Set.prototype.union === "function") console.log([...new Set([1, 2]).union(new Set([2, 3]))]); // [1, 2, 3]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.