Remove Duplicates from Array in JavaScript
You're tasked with creating a JavaScript function that efficiently removes duplicate elements from an array. This is a fundamental operation in data manipulation, often encountered when cleaning datasets, optimizing storage, or preparing data for further processing. Your solution should handle various data types and edge cases gracefully.
Problem Description
Your goal is to implement a JavaScript function named removeDuplicates that accepts a single argument: an array. This function should return a new array containing only the unique elements from the input array, preserving the original order of the first occurrence of each element.
Key Requirements:
- The function must return a new array. The original input array should not be modified.
- The order of elements in the returned array must be the same as their first appearance in the input array.
- The function should be able to handle arrays containing various data types, including numbers, strings, booleans,
null,undefined, and even objects (where uniqueness is determined by reference for objects).
Expected Behavior:
Given an array, the function should identify and include each unique element exactly once in the output array.
Edge Cases to Consider:
- An empty input array.
- An array with no duplicate elements.
- An array where all elements are duplicates.
- An array containing mixed data types.
- An array containing
nullorundefinedvalues. - An array containing identical objects (they should be considered duplicates if they are the same object reference).
Examples
Example 1:
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
Explanation: The duplicate occurrences of 2 and 4 are removed, and the order of the remaining elements is preserved.
Example 2:
Input: ["apple", "banana", "apple", "orange", "banana", "grape"]
Output: ["apple", "banana", "orange", "grape"]
Explanation: Duplicate strings "apple" and "banana" are removed, maintaining the original order of their first appearance.
Example 3:
Input: [true, false, true, null, undefined, null]
Output: [true, false, null, undefined]
Explanation: Demonstrates handling of boolean, null, and undefined values.
Example 4:
Input: []
Output: []
Explanation: An empty input array should result in an empty output array.
Constraints
- The input will always be a JavaScript array.
- The array can contain any valid JavaScript data type.
- The function should aim for an efficient solution, ideally with a time complexity better than O(n^2) if possible.
Notes
Consider different JavaScript data structures or methods that can help you track seen elements efficiently. Remember that the requirement to preserve order is crucial. Think about how you can iterate through the array and decide whether to include an element in the result based on whether you've encountered it before.