Method 1: double for the cycle to re-
loop through the array in each unit cell is compared with that later, if the same unit after it's deleted
Note: To prevent the collapse of the array
var arr = [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5];
for(let i = 0 ; i <= arr.length-1 ; i++){
for(let j = i+1 ; j <= arr.length-1 ; j++){
if(arr[i] === arr[j]){
arr.splice( j , 1 );
j--;
}
}
}
console.log(arr);
Method 2: value of sorting the array, two adjacent unit compares
long as a weight for loop
var arr = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5];
arr = arr.sort(function(a,b){return a-b});
for(let i = 0 ; i <= arr.length-1-1 ; i++){
if(arr[i] === arr[i+1]){
arr.splice(i+1 , 1);
i--;
}
}
console.log(arr);
Method 3: Using the object, the name of the same key can not be stored
var arr = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5];
const obj = {};
arr.forEach(function(val,key){
obj[val] = '随便';
});
const newArr = [];
for(let key in obj){
newArr.push(key);
}
console.log(obj);
console.log(newArr);
Method 4: indexOf method of
determining the value to be written, whether already present in the new array
var arr = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5];
const newArr = [];
for(let i = 0 ; i <= arr.length-1 ; i++){
if( newArr.indexOf(arr[i]) == -1 ){
newArr.push(arr[i]);
}
}
console.log(newArr);
Method 5: array unit, the data type assigned to SET
the same data type SET does not store data, automatically deduplication
var arr = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5];
const set = new Set(arr);
const newArr = [...set];
const newArr = [...new Set(arr)];
console.log(newArr);