Remove Duplicates from Flat Array in with JavaScripts Set Data Structure

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

In this lesson you will learn how to remove duplicates from the flat array which is a common coding challenge for beginner JavaScript interviews.

We will employ the easiest and one of the fastest duplicate removal methods with the help of Set. Set is a data structure in JavaScript that only allows unique elements to be stored within it. By converting an Array to a Set and then back to an Array you'll see how we can easily filter out duplicates.

Instructor: [00:00] In the interview, you are asked to remove duplicates from the flat array, which looks something like this. We have a basket of fruits, which contains couple of apples, couple of pears and a pineapple.

[00:11] What we want to get is the function, which would accept this array and return an array of one apple, one pear and one pineapple, so the duplicates are removed. Let's see how we can do that. The first way is to use the set. Let's go through the steps and then write the function for that. Let's first see what set is.

[00:34] Const set is new set of basket and let's console log set. You see that we get a set which is already with the removed duplicates. We can confirm that with using the native property size. We see that the size of the set is three, which is exactly apple, pear and pineapple, but we want to get an array.

[01:08] We then need to somehow convert this set into an array, on set array. The easiest way to do that is to spread the set inside of the array. If you look, set array, we see that we get an array of apple, pear and pineapple.

[01:31] Let's write the function for that, onset function equals. We want to get an array as an argument and then we want to return an array, we spread it, new set of baskets. To confirm that it works, let's console set function. Then of course, use not basket but an array that we pass. Let's pause basket here. You see that we get the same result.

[02:13] Let's try something else. Let's say we have an array of integers and there are lots of duplicates there. Any integers we pass, it actually only gives us an array of the ones which are unique. This is how you remove duplicate function with a set.