AniUI Academy

Union several arrays, first appearance wins

mediumArrays & Objects+250 XPPractice

Combining a user's saved filters with the defaults and with whatever the URL asked for gives you three arrays that overlap. You want one list, no repeats, and an order that feels stable.

Implement union(...arrays) taking any number of arrays as separate arguments. Return a single array containing every value from every input, deduplicated, in the order each value first appeared when reading the arrays left to right and each array front to back. Values are compared the way a Set compares them. Duplicates inside a single array are removed too. Empty arrays contribute nothing, and calling union() with no arguments returns an empty array. Never modify the inputs.

Arguments

...arraysArray[]
Any number of arrays to merge, passed as separate arguments.

Returns

Array — A single array of each distinct value, placed at its first appearance across all inputs.

Examples

union([1, 2], [2, 3]);
// [1, 2, 3]
union([3], [1, 3], [2, 1]);  // [3, 1, 2] — first-appearance order
union([1, 1, 2]);            // [1, 2] — dedupes within a single array
union();                     // []

What it has to do

  • Accept a variable number of array arguments.
  • Include each distinct value once, at the position of its first appearance.
  • Deduplicate within a single array as well as across arrays.
  • Return [] when called with no arguments.
  • Do not mutate any input array.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.