DEV Community

Justin
Justin

Posted on

JS Challenge: Remove duplicates from an array

The first method below creates a new Set object with the elements of the array which eliminates all duplicates since a Set by definition cannot have duplicate elements. Then using the Spread operator creates a new Array from the elements of the Set.

The second method uses Array filter() method to filter out multiple occurrences of the same element - keeping only the first occurrence.

const arr = [1, 1, 2, 3, 3, 4, 4, 5];

let uniqueArr = [...new Set(arr)];

// OR this works too

uniqueArr = arr.filter((value, index, self) => 
  self.indexOf(value) === index);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️