一、利用ES6的Set方法去重?
1 let arr = [1,0,0,2,9,8,3,1];
2 function unique(arr) {
3 return Array.from(new Set(arr))
4 }
5 console.log(unique(arr));
or
6 console.log(...new Set(arr));
二、使用双重for循环,再利用数组的splice方法去重(ES5常用)
var arr = [1, 5, 6, 0, 7, 3, 0, 5, 9,5,5];
function unique(arr) {
for (var i = 0, len = arr.length; i < len; i++) {
for (var j = i + 1, len = arr.length; j < len; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
j--;
len--;
}
}
}
return arr;
}
console.log(unique(arr));
三、利用数组的indexOf方法去重
var arr =[1,-5,-4,0,-4,7,7,3];
2 function unique(arr){
3 var arr1 = [];
4 for(var i=0,len=arr.length;i<len;i++){
5 if(arr1.indexOf(arr[i]) === -1){
6 arr1.push(arr[i]);
7 }
8 }
9 return arr1;
10 }
11 console.log(unique(arr));
四、利用数组的includes去重
var arr = [-1,0,8,-3,-1,5,5,7];
2 function unique( arr ){
3 var arr1 = [];
4 for(var i=0,len=arr.length;i<len;i++){
5 if( !arr1.includes( arr[i] ) ){
6 arr1.push(arr[i]);
7 }
8 }
9 return arr1;
10 }
11 console.log(unique(arr));