DEV Community

Cover image for Removing duplicate elements in Javascript: In a simple way! 😡
Maria Antonella πŸ¦‹
Maria Antonella πŸ¦‹

Posted on

Removing duplicate elements in Javascript: In a simple way! 😡

The last few weeks I have been learning Python. I'm following this roadmap: 30-days-of-python Series' Articles by @arindam Dawn. I recommend it ! I love it 🀩

Anyway, when I was learning Python I saw that the SET framework existed, and I was fascinated.
But thanks to that I discovered that it also existed in Javascript, and I didn't know it!

With SET we can remove duplicate elements from an array in a very easy way.

JavaScript's built-in Set object is described as a collection of values, where each value may occur only once. A Set object is also iterable, making it easily convertible to an array using the spread (...) operator.

🍭 Here are some examples of this:

const nums = [1, 2, 2, 3, 1, 2, 4, 5, 5, 6, 4, 2, 6];
[...new Set(nums)] // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
const something = ['anto', 'anto', 'antonella', 'ant', 'ant', 2, 4, 5, 6,2,2];
[...new Set(something)] // [ 'anto', 'antonella', 'ant', 2, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode
const emojisFruits = ['πŸ‹','πŸ‹', 'πŸ‡ ','πŸ‰' ,'πŸ‡ ','πŸ“' ,'πŸ’','πŸ’','🍈 ','πŸ’'];
[...new Set(emojisFruits)] // [ 'πŸ‹', 'πŸ‡ ', 'πŸ‰', 'πŸ“', 'πŸ’', '🍈 ' ]
Enter fullscreen mode Exit fullscreen mode

Very useful!!!
Did you also know about this?

Top comments (9)

Collapse
 
codewithnithin profile image
codeWithNithin

nice.
for higher order function lovers , we can do the same thing by

const nums = [1, 2, 2, 3, 1, 2, 4, 5, 5, 6, 4, 2, 6];
nums.filter((v,i) => nums.indexOf(v) == i  );
Enter fullscreen mode Exit fullscreen mode
Collapse
 
henryjw profile image
Henry Williams • Edited

Like @lukeshiru said, this works but is much slower. O(n^2) vs O(n). It's fine for small arrays, but would be slow as the array gets bigger.

Collapse
 
ngnam profile image
NamNguyen

numsObject = [{id: 1, name: 'one', {id: 2, name: 'two'}] ?

Collapse
 
kevingamaa profile image
Kevin Smith

new Map(arr) is so mush faster than this

Collapse
 
vikasukani profile image
Vikas Ukani

That's really simplest way to make a unique list.

Collapse
 
hyggedev profile image
Chris Hansen

Thanks for this tip! πŸ’― I saw it once, absolutely forgot about it. How useful! And it's freaking easy!✌️

Collapse
 
justaguyfrombr profile image
Misael Braga de Bitencourt

Awesome!!

Thanks!!

Collapse
 
magecoder profile image
Andre Schubert

nice, thx for the tip

Collapse
 
suhagsarak profile image
Suhag Sarak

I used in my school