Extracting Unique Elements from an Array
Working with arrays often involves dealing with duplicate values. Being able to efficiently extract only the unique elements from an array is a common and useful task in data processing and manipulation. This challenge will test your ability to identify and return distinct values from a given array.
Problem Description
Your task is to write a Javascript function that takes an array as input and returns a new array containing only the unique values from the original array. The order of the unique elements in the output array does not strictly matter, but it's generally good practice to maintain the order of their first appearance.
Key Requirements:
- The function should accept a single argument: an array.
- The function should return a new array.
- The returned array must contain only the unique elements from the input array.
- Duplicate values should be removed.
Expected Behavior:
Given an input array, the function should produce an output array where each element appears only once.
Edge Cases to Consider:
- An empty input array.
- An array containing only duplicate values.
- An array with mixed data types (numbers, strings, booleans, null, undefined, objects, etc.).
Examples
Example 1:
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
Explanation: The duplicate values 2 and 4 have been removed, leaving only the unique elements.
Example 2:
Input: ["apple", "banana", "apple", "orange", "banana", "grape"]
Output: ["apple", "banana", "orange", "grape"]
Explanation: The duplicate strings "apple" and "banana" are removed.
Example 3:
Input: [true, false, true, null, undefined, null]
Output: [true, false, null, undefined]
Explanation: Different data types are handled, and duplicates of `true` and `null` are removed.
Constraints
- The input array can contain any valid JavaScript data type.
- The input array can have a length between 0 and 1,000,000 elements.
- Your solution should aim for reasonable performance, ideally with a time complexity that scales efficiently with the size of the input array.
Notes
Consider different approaches to solving this problem. JavaScript offers several built-in methods and data structures that can be leveraged. Think about how you might keep track of elements you've already encountered.