1. The most basic deduplication method
Idea: Define a new array and store the first element of the original array, then compare the element group with the elements of the new array one by one, and store them in the new array if they are different.
function unique(arr){
var res = [arr [0]];
for(var i=1;i<arr.length;i++){
var repeat = false;
for(var j=0;j<res.length;j++){
if(arr[i] == res[j]){
repeat = true;
break;
}
}
if(!repeat){
res.push(arr[i]);
}
}
return res;
}
2. Sort first before deduplication
Idea: sort the original array first, compare it with the adjacent ones, and store them in the new array if they are different
function unique(arr){
var arr2 = arr.sort ();
var res = [arr2 [0]];
for(var i=1;i<arr2.length;i++){
if(arr2[i] !== res[res.length-1]){
res.push(arr2[i]);
}
}
return res;
}
3. Use the properties of the object to deduplicate (recommended)
Idea: Take out the elements of the original array each time, and then access this property in the object, if it exists, it means repetition
function unique(arr){
var res =[];
var json = {};
for(var i=0;i<arr.length;i++){
if(!json[arr[i]]){
res.push(arr[i]);
json[arr[i]] = 1;
}
}
return res;
}
4. Use subscript query
function unique(arr){
var newArr = [arr[0]];
for(var i=1;i<arr.length;i++){
if(newArr.indexOf(arr[i]) == -1){
newArr.push(arr[i]);
}
}
return newArr;
}