Home > Article > Web Front-end > What is the method to remove duplication from es6 array?
es6 array deduplication method: 1. Use the Set object and the from method of the array, the syntax "Array.from(new Set(arr))"; 2. Use the Set and the expansion operator, the syntax "[ ...new Set(arr)]"; 3. Use the filter method of Map object and array.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
The first one: using the Array.from method of Set object and array
const newArr = Array.from(new Set(arr));
Code example:
Print the results after running
To put it simply, the second method is simpler than the first. Let’s explain it briefly as well.
Set is a new data structure provided by ES6, is similar to an array, but has no duplicate values.
The Array.from method is used to convert two types of objects into real arrays: array-like objects and iterable objects ( Including ES6's new data structures Set and Map).
So set combined with Array.from can also achieve the effect of array deduplication. However, it should be noted that mainstream browsers such as Chrome, Firfox, Opera, Safari, including Microsoft Edge, all support it, but only the IE series does not support it.
Second method: Use the Set expansion operator...
The third method can be said to be simpler
const newArr = [...new Set(arr)];
Code example:
Print the result after running
These are three ways to use the new features of ES6 to achieve array deduplication. These three The common advantage of these methods is that the code is concise, and the effect of deduplication can also be achieved for undefined and NaN~~
Third method: Use the filter method of Map objects and arrays
function unique(arr) { const res = new Map(); return arr.filter((a) => !res.has(a) && res.set(a, 1)) }
Code example:
Printed result
By printing we found that the effect we wanted was indeed achieved. So let’s briefly explain it below.
The Map object is a new data structure provided by ES6. The has method is to return a Boolean value to indicate whether a certain value exists in the current MP object. The set method is It is to set the key/value for the Map object.
2 The filter() method creates a new array. The elements in the new array are checked for all elements in the specified array that meet the conditions.
So, the Map object combined with the filter method can achieve the effect of array deduplication~
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of What is the method to remove duplication from es6 array?. For more information, please follow other related articles on the PHP Chinese website!