数组中去重的方法很多,我这里介绍几种经常见到的情况以及常用的方法。
1.普通的单层结构数组
var arr=[1,2,3,4,2,1,3,4,2,1,5,7,8,2,3,4,5,1]; var arr1=[]; for(var i=0,bool=false;i<arr.length;i++){ for(var j=0,bool=false;j<arr1.length;j++){ if(arr[i]===arr1[j]){ bool=true; break; } } if(!bool) arr1.push(arr[i]); } console.log(arr,arr1)
2.有对象的数组
var arr=[ {a:1,b:2}, {a:1,b:2}, {a:2,b:2}, {a:1,b:4}, {a:4,b:2}, {a:2,b:2}, ]; var arr1=[]; for(var i=0,bool=false;i<arr.length;i++){ for(var j=0,bool=false;j<arr1.length;j++){ if(JSON.stringify(arr[i])===JSON.stringify(arr1[j])){ bool=true; break; } } if(!bool) arr1.push(arr[i]) } console.log(arr,arr1)
3.多个数组去重
var arr=[1,2,3,4,5,6]; var arr1=[2,3,5]; var arr2=[]; for(var i=0,bool=false;i<arr.length;i++){ for(var j=0,bool=false;j<arr.length;j++){ if(arr[i]===arr1[j]){ bool=true; break; } } if(!bool) arr2.push(arr[i]) } console.log(arr2)
数组的去重方法还有很多,情况也还有很多,后面想起来的话,再补充。