- When working with arrays, in some cases do we need to remove duplicate elements? There are many ways to solve the above problem, today I will introduce to you 3 simple ways to remove duplicate elements.
- Here are 3 ways to remove duplicate elements in the array, using Set , filter , reduce . To understand more we will learn each way.
- We will go into what is Set ?
– Set is a new data object introduced in ES6. Set allows to store only values. So when passed into an array, it will delete all duplicate values
- Okay, back to our code and apply Set . There are 2 steps when using Set :
- First, we create a new Set from the array. Because Set only allows to store unique values, duplicates will be deleted.
- Now that the duplicates have been deleted, we will convert them back into arrays using the math operator …
- We can use Array.from to convert Set to Array :
- The next way I would recommend using filters . First, we need to understand the following two methods:
- indexOf : This method returns the first position it finds of the element provided from the array.
- filter : This method will create a new array of elements that meet the condition.
- Let’s see what happens when we loop through the array:
- Here is the output from the above code. Duplicate elements whose index does not match indexOf will therefore not satisfy the condition and cannot be contained in the filter array.
- We can also filter out duplicates by the following way:
- Output for the above code:
- The last way I would recommend you is to use reduce .
- reduce is a method used to shorten array elements and combine them into final arrays based on a number of reducer functions.
- In our problem, the reducer function is checking whether the final array contains an item. If it does not, store the item in the final array. If not, skip the item and return the final array.
- Using reduce can be a little harder to understand, so take a look at the following code:
- And here is the output from console.log:
- So I have introduced you 3 ways to remove duplicate elements in the array. And the way I often use it is Set because it’s short and easy to understand. =))
- Thank you for reading!
- Reference source: https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c