preface
There are many cases where we need to deduplicate the data returned by the server. What are the methods to achieve this? This article lists six solutions and takes a look at what they are
A, requirements,
Array deduplication, each element in the array can only appear once.
Second, solutions
1. Set
ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.
The members of the set method must be unique enough to meet our needs.
The code is as follows (example) :
let arr = [1.2.3.4.3.2.3.4.6.7.6];
let unique = (arr) = > [...new Set(arr)];
console.log(unique(arr)) [1, 2, 3, 4, 6, 7]
Copy the code
2. The reduce () method
Use the reduce method provided by the JS built-in object Array to reduce method use details can see my blog: Array common method code is as follows (example) :
let arr = [1.2.3.4.3.2.3.4.6.7.6];
const res = arr.reduce((acc,cur) = > {
if(acc.indexOf(cur) === -1){
acc.push(cur)
}
return acc
},[])
console.log(res) [1, 2, 3, 4, 6, 7]
Copy the code
3. Double for loop
J ==result.length = j= result.length = j= result.length = j= result.length = j= result.length = j= result.length
The code is as follows (example) :
let arr = [1.2.3.4.3.2.3.4.6.7.6];
let result = [];
for(var i = 0; i < arr.length; i++) {
for(var j = 0 ; j < result.length ; j++) {
if(arr[i] === result[j]){
break;
};
};
if(j == result.length){
result.push(arr[i]);
};
};
console.log(result); [1, 2, 3, 4, 6, 7]
Copy the code
4. The splice () method
Use the splice method provided by the built-in JS object Array
The code is as follows (example) :
let arr = [1.2.3.4.3.2.3.4.6.7.6];
function unique(arr){
for(var i = 0; i<arr.length; i++){
for(var j = i+1; j < arr.length; j++){
if(arr[i] == arr[j]){
arr.splice(j, 1); j--; }}}return arr;
}
console.log(unique(arr))
Copy the code
5. The filter () method
Use the splice method provided by the built-in JS object Array
The code is as follows (example) :
let arr = [1.2.3.4.3.2.3.4.6.7.6]
let unique = (arr) = > {
return arr.filter((item,index) = > {
return arr.indexOf(item) === index
})
}
console.log(unique(arr)) [1, 2, 3, 4, 6, 7]
Copy the code
6. Map
Map data structure is used for de-weighting
The code is as follows (example) :
let arr = [1.2.3.4.3.2.3.4.6.7.6]
let unique = (arr) = > {
let seen = new Map(a)return arr.filter((item) = > {
return! seen.has(item) && seen.set(item,1)})}console.log(unique(arr)) [1, 2, 3, 4, 6, 7]
Copy the code
conclusion
Very practical method, remember to like collection oh ~