【 译 文】medium.com/dailyjs/how…
There are three ways to deduplicate an array and return a unique value. I like to use Set because it’s quick and easy.
1.Set
First, what is a Set
Set
is a new data object introduced in ES6. Because Set only lets you store unique values. When you pass in an array, it will remove any duplicate values.
Set is a new data object introduced in ES6. Because a Set only allows you to store unique values. Pass in an array and return any duplicate values.
Let’s go back to the code and break down what happened. Divided into 2 steps:
- First, create a new one by passing in an array
Set
Because theSet
Only unique values are allowed, and all duplicate values are removed. - Now that the repeated values are gone, we deconstruct the symbol
.
Convert it to an array.
withArray.from
将 Set
Convert to an array
Alternatively, you can also convert a Set to an Array using array. from:
2: using Filer
To understand this option, let’s look at two methods: indexOf and filter.
indexOf
The indexOf method returns the indexOf the first element found in the array.
filter
The filter() method creates a new array element, passing the condition we provide. In other words, if the element passes and returns true, it will be included in the filtered array. And any element that fails or returns false will not be in the filtered array.
As we loop through the array, let’s y step by step and iterate over what happens.
Here is the output from the display console. Duplicates are where an index does not match an indexOf. Therefore, in these cases, the condition will be false and will not be included in our filter array.
Retrieve duplicate values
We can also use the Filter method to retrieve duplicate values from the array. We can do this by simply adjusting our conditions:
Next, jump out of the code and look at the output.
3: use the Reduce
The Reduce method is used to execute a Reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value. In this case, our reduction function checks to see if our final array contains the item. If not, push it into our final array. Otherwise, skip the element and return the final array as is (actually skip the element). Reduce is more difficult to understand, so let’s also look at the output in each case:
Here is the output from console.log
The resources
- MDN Web Docs — Set
- MDN Web Docs — Filter
- MDN Web Docs — Reduce
- GitHubGist: Remove duplicates from JS array
- CodeHandbook: How to Remove Duplicates from JavaScript Array