Removing duplicates from arrays is a common task in JavaScript. Here are several effective methods to accomplish this.
Method 1: Using Set (Recommended)
The simplest and most performant way to remove duplicates is using a Set:
Pros:
- Clean and concise
- Good performance O(n)
- Works with primitive values
Cons:
- Only works with primitive values (numbers, strings, booleans)
- Objects are compared by reference
Method 2: Using Filter
For more complex scenarios or when you need to keep the first occurrence:
Pros:
- More flexible for custom logic
- Easy to understand
Cons:
- Less performant O(nยฒ) due to
indexOf
Method 3: Using Reduce
A functional approach using reduce:
Pros:
- Functional programming style
- Can be combined with other transformations
Cons:
- Less performant due to
includes - More verbose
Method 4: For Objects (Using Map)
When dealing with objects, you need to compare by a specific property:
Pros:
- Works with objects
- Can specify which property to use for uniqueness
- Good performance
Cons:
- More complex syntax
- Keeps the last occurrence (can be modified to keep first)
Performance Comparison
For large arrays (10,000+ elements):
- Set: ~1ms (fastest)
- Map (for objects): ~2ms
- Reduce: ~50ms
- Filter: ~100ms (slowest)
Recommendation
- Use Set for primitive values (numbers, strings, booleans)
- Use Map for objects when you need to deduplicate by a specific property
- Use Filter or Reduce only when you need custom logic or are working with small arrays
Note: All these methods create a new array. If you need to modify the original array in place, you'll need a different approach.