StackDevLife
πŸ’‘Daily Dev TipBeginnerJavaScript

Array Deduplication Challenge (3 Ways)

~1 min read
πŸ’‘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:

  1. Using Set
  2. Using filter
  3. 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 β†’