Problem Statement
Write a function that removes duplicates from an array and returns a new array with unique elements only.
Examples
Input: [1, 2, 3, 4, 5]
Output: [1, 2, 3, 4, 5]
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
Input: [1, 1, 1, 1, 1]
Output: [1]
Input: []
Output: []
Approach
- Create an empty array to store unique elements.
- Iterate through the input array.
- Check if the current element is already in the unique array.
- If it is not, add it to the unique array.
- Return the unique array.
Code
Explanation
-
We use the Set object to store unique elements.
-
The Set object is a built-in JavaScript data structure that stores unique values of any type.
-
When we create a new Set from an array, it automatically removes all duplicate elements:
- If we pass
[1, 2, 2, 3, 4, 4, 5] to a new Set, it will only store 1, 2, 3, 4, 5.
-
Here's how it works internally:
- As each element is added to the Set, it checks if that value already exists.
- If the value is new, it's added to the Set.
- If the value already exists, it's ignored.
-
This property of Set makes it perfect for removing duplicates from an array.
-
Example:
- We use the spread operator
... to convert the Set back to an array.
- This approach ensures that all duplicate elements are removed.
Time Complexity
The time complexity of this solution is O(n), where n is the number of elements in the input array. This is because we need to iterate through the array to check if the current element is already in the unique array.
Space Complexity
The space complexity of this solution is O(n), where n is the number of elements in the input array. This is because we need to store the unique elements in a new array.
Conclusion
The solution is efficient and straightforward, leveraging the Set object to remove duplicates. This approach ensures that all duplicate elements are removed, and the resulting array contains only unique elements.