JS数组去重
过滤器和indexof
var arr = [2,3,4,4,5,2,3,6];
var arr2 = arr.filter(function(element,index,self){
return self.indexOf(element) === index;
});
console.log(arr2); //[2, 3, 4, 5, 6]
循环和indexof
var arr = [2,3,4,4,5,2,3,6],
arr2 = [];
for(var i = 0;i< arr.length;i++){
if(arr2.indexOf(arr[i]) < 0){
arr2.push(arr[i]);
}
}
console.log(arr2);//[2, 3, 4, 5, 6]
把数组的值作为对象的键
var arr = [0,2,3,4,4,0,2];
var obj = {};
var tmp = [];
for(var i = 0 ;i< arr.length;i++){
if( !obj[arr[i]] ){
obj[arr[i]] = 1;
tmp.push(arr[i]);
}
}
console.log(tmp); //[0, 2, 3, 4]
利用数组的循环和includes方法
var arr = [0,2,3,4,4,0,2];
var res = [];
for(var i=0; i<arr.length; i++){
if( !res.includes(arr[i]) ){ // 如果res新数组包含当前循环item
res.push(arr[i]);
}
console.log(res);
利用数组的filter和includes
var arr = [0,2,3,4,4,0,2];
var res = [];
res = arr.filter(function(item){
return res.includes(item) ? '' : res.push(item);
});
利用es6的set方法
var arr = [0,2,3,4,4,0,2];
var arr2=Array.from(new Set(arr));
console.log(arr2);
网友评论