JavaScript Array Union
This challenge will test your ability to combine multiple arrays into a single, unique collection of elements. This is a common operation in data processing and programming, where you might need to merge data from different sources without duplication.
Problem Description
Your task is to create a JavaScript function that accepts an arbitrary number of arrays as input and returns a new array containing all unique elements from all input arrays. The order of elements in the output array is not strictly defined, but it's generally good practice to maintain a consistent order if possible (e.g., the order in which they first appear across all input arrays).
Key Requirements:
- The function should accept any number of arrays as arguments.
- The output must be a single array.
- The output array should contain only unique elements. Duplicates should be removed.
- The function should handle arrays containing various data types (numbers, strings, booleans, null, undefined, etc.).
Expected Behavior:
The function should correctly identify and include each distinct element from all provided input arrays exactly once in the returned array.
Edge Cases to Consider:
- Empty input arrays.
- An empty set of input arrays (no arguments passed).
- Arrays containing duplicate elements within themselves.
- Arrays containing elements of mixed data types.
Examples
Example 1:
Input: [1, 2, 3], [2, 4, 5], [3, 5, 6]
Output: [1, 2, 3, 4, 5, 6]
Explanation: The unique elements from all three arrays are combined. 1 is from the first, 2 and 3 are from the first and appear again in others, 4 is from the second, and 5 and 6 are from the second and third respectively.
Example 2:
Input: ['a', 'b'], ['b', 'c', 'd'], ['e']
Output: ['a', 'b', 'c', 'd', 'e']
Explanation: All unique string elements from the input arrays are collected.
Example 3:
Input: [], [1, 1, 2], [null, undefined, 2, null]
Output: [1, 2, null, undefined]
Explanation: Handles empty arrays, internal duplicates, and various data types including null and undefined.
Constraints
- The total number of elements across all input arrays will not exceed 1,000,000.
- Each input array will contain elements of primitive data types (numbers, strings, booleans, null, undefined, symbols) or simple objects/arrays where equality is determined by reference.
- The solution should aim for a time complexity that is efficient for the given constraints, ideally better than O(n*m) where n is the number of arrays and m is the average length of an array if n is large.
Notes
Consider how you might efficiently track elements you've already encountered to avoid duplicates. JavaScript's Set object can be particularly useful for this. Think about how to iterate through multiple arrays and collect their elements.