call(back)
Algorithms & Data StructureseasySign in to star problems

Unique Values Across Two Arrays III

Concatenate two arrays of objects and keep one object per value of the property key: unionBy(a, b, key). The first object with each key wins, and the result keeps first-seen order.

unionBy([{ id: 1, n: "a" }, { id: 2, n: "b" }], [{ id: 2, n: "B" }, { id: 3, n: "c" }], "id")
  // [{ id: 1, n: "a" }, { id: 2, n: "b" }, { id: 3, n: "c" }]

Hints

Hint 1

A Set of objects compares references, so two equal-looking objects both survive. Track the keys instead.

Hint 2

Keep a set of keys already taken and push an object only when its key is new.

Asked at