Can you remove duplicate values from an array using 3 different approaches in JavaScript?
Today’s challenge is simple but powerful 👇
You have an array:
const arr = [1, 2, 2, 3, 4, 4, 5];Your task:
Remove duplicates using 3 different approaches.
Try these methods:
- Using Set
- Using filter
- Using reduce
Expected Output:
[1, 2, 3, 4, 5]Bonus:
- Maintain original order
- Try with objects (hard mode)
Solutions:
// 1. Using Set
const unique1 = [...new Set(arr)];
// 2. Using filter
const unique2 = arr.filter((item, index) => arr.indexOf(item) === index);
// 3. Using reduce
const unique3 = arr.reduce((acc, curr) => {
if (!acc.includes(curr)) acc.push(curr);
return acc;
}, []);Which one is fastest? Try benchmarking!
More Daily Dev Tips
Stop Using map() for Side Effects
Using Array.map() for side effects leads to confusing code and unnecessary memory usage.
💡Don’t Hide Errors Behind Generic Toasts
A “Something went wrong” message helps nobody. Log the real error and show users what they can do next.
💡Always Add Timeouts to External API Calls
Never call external APIs without a timeout — one slow dependency can freeze your entire system.
Get a new Daily Dev Tip in your inbox
Subscribe to Stack Dev Life — free, no spam, unsubscribe anytime.
Subscribe free →