π‘TL;DR
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:
JavaScript
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:
JavaScript
[1, 2, 3, 4, 5]Bonus:
- Maintain original order
- Try with objects (hard mode)
Solutions:
JavaScript
// 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!
JavaScriptArrayInterviewChallengeBeginner
π‘
Get a new Daily Dev Tip in your inbox
Subscribe to Stack Dev Life β free, no spam, unsubscribe anytime.
Subscribe free β