DEV Community

Cover image for How to Remove Duplicates from Arrays

Posted on

How to Remove Duplicates from Arrays


Okay, you want to remove duplicates from your array. As a beginner this might prove a difficult task. Luckily, Ruby has created more than one way to do this, so you don't spend your time writing a function for it. Let's get into it.

Duplicates, Duplicates, Duplicates...

So, what are these methods anyway? Well, since you asked so nicely you can use the unique method (.uniq), the difference operator(-), the union operator(|), and the intersection operator(&), your own short-hand method(which we'll get into later), and to_set.

Let's Start From the Start, Syntax

Let's take a look at the syntax for each method.

Let's see how they work

You better work!


The operators

These three operators have different uses. The Difference operator returns items from the first array that DON'T appear in the second and vice versa. The Union operator can be used to return one of each item in both arrays, which guarantees that there will not be any duplicates. The Intersection operator returns items that appear in both arrays, also without duplicates.
After all I've said you're probably thinking,
"I don't care, get to the point!"
but to your surprise there actually is a reason that I'm telling you this. Here, let me show you.

Don't worry you're almost to_set!

The to_set method is a lot simpler than the previous methods. You have likely already learned what a set is, but for those who haven't a quick recap.
Here we go again!



Sets are unordered lists that can't have duplicates. So the to_set method creates an instance of the array to a set. Making all the duplicates disappear. So you can assign the variable to the duplicate free list.

to_set usage

Let's see!

Finally, what I've been waiting to write!



It's not the end yet, but now we get to see a all the ways mentioned before and my own custom method in action.

Mine is not as good, for it to work it has to return the array sorted. Anyway, all this reading is probably boring you so I hope you liked this post, if you have any questions put them in the comments.

BYE ;)

Top comments (0)