1. Refer to answer 1: Use ES6 to add data type Set
A Set is similar to an array, but the values of its members are unique and have no duplicate values.
function uniq(arry) {
return [...new Set(arry)];
}
Copy the code
2. Refer to answer 2: Use indexOf
function uniq(arry) {
var result = [];
for (var i = 0; i < arry.length; i++) {
if (result.indexOf(arry[i]) === -1) {
// If result does not contain arry[I], add it to array
result.push(arry[i])
}
}
return result;
}
Copy the code
3. Reference 答案 3: use includes
function uniq(arry) {
var result = [];
for (var i = 0; i < arry.length; i++) {
if(! result.includes(arry[i])) {// If result does not contain arry[I], add it to array
result.push(arry[i])
}
}
return result;
}
Copy the code
4. Take advantage of reduce
function uniq(arry) {
return arry.reduce((prev, cur) = > prev.includes(cur) ? prev : [...prev, cur], []);
}
Copy the code
5. Refer to answer 5: Use Map
function arrayNonRepeatfy(arr) {
let hashMap = new Map(a);let result = new Array(a);// The array is used to return the result
for (let i = 0; i < arr.length; i++) {
if(hashMap.has(arr[i])) { // Check whether the key exists in the hashMap
hashMap.set(arr[i], true); // True indicates that the key is duplicated in the original array, false vice versa
} else { // If the key does not exist in the hashMap, add it
hashMap.set(arr[i], false); result.push(arr[i]); }}return result;
}
Copy the code
Welcome to pay attention to my public account “front-end history robbery Road”
Reply keyword e-books, you can get nearly 12 front-end popular e-books.
Reply keywords little Red Book 4th edition, you can get the latest “JavaScript advanced Programming” (4th edition) ebook.
You can also add me to wechat. I have wooed many IT bigwigs and created a technical exchange and article sharing group. Welcome to join.
Author: Vam’s Golden Bean Road
Main area: front-end development
My wechat account is Maomin9761
Wechat public number: the front end of the road through robbery