How to remove array duplicates in ES6

Tram Ho

Question

  • 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.

Solution

  • Here are 3 ways to remove duplicate elements in the array, using Set , filter , reduce . To understand more we will learn each way.

Using Set

  • 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 :
    1. First, we create a new Set from the array. Because Set only allows to store unique values, duplicates will be deleted.
    2. 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 :

Using filter

  • The next way I would recommend using filters . First, we need to understand the following two methods:
    1. indexOf : This method returns the first position it finds of the element provided from the array.
    2. 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:

Using reduce

  • 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:

summary

Share the news now

Source : Viblo