Removing duplicates is one of those things we need to do somewhat frequently but we also want to make sure we do it efficiently. Doing it by hand can easily lead to inscrutable code and a lurking performance issue. Typically, in JavaScript we’ll be removing duplicates from an array since that’s our typical go-to data structure.
So here’s a very cool and tricky way to remove duplicates from an array with just one line of code.
The first piece we need is the Set object. This is one of the new objects available in recent versions of JavaScript. It’s something we don’t typically use much. The Set object is very cool because it’s a collection a little like an array, but it ONLY allows unique items. If we try to add a duplicate item to its collection, then it just silently doesn’t add the item. So if we give it five 3’s, then it’ll only have one item in it, a single 3.
The Set object’s constructor will take in any iterable object, which includes arrays. So we can give a Set an array, and it’ll load in the elements and any duplicates won’t get loaded. We do that like this:
Now that we have a Set with the unique items we want, we just need to turn that back into an array. Here the Array.from method comes to the rescue. This static method will take any array-like or iterable object, and create a new array from it. So when we pass in our Set to Array.from, it’ll create a new array with the elements of the Set.
So combining these, in a single line of code, we can remove duplicates from an Array with nice, concise code.
Happy Coding!
Signup for my newsletter at here.
Visit Us: thinkster.io | Facebook: @gothinkster
| Twitter: @gothinkster
Top comments (0)