问题:数组对象去重
var arr = [{name: ‘a’,id: 1}, {name: ‘a’,id: 2}, {name: ‘b’,id: 3}, {name: ‘c’,id: 4}, {name: ‘c’,id: 6}, {name: ‘b’,id: 6}, {name: ‘d’,id: 7}];
对数组对象name进行去重处理, 结果显示为:
[{name: ‘a’,id: 1}, {name: ‘b’,id: 3}, {name: ‘c’,id: 4}, {name: ‘d’,id: 7}];
方法一:es5冒泡排序法,去重arr
vararr=[{name:‘a’,id:1},{name:‘a’,id:2},{name:‘b’,id:3},{name:‘c’,id:4},{name:‘c’,id:6},{name:‘b’,id:6},{name:‘d’,id:7}];functiondeWeight(){for(vari=0;i<arr.length-1;i++){for(varj=i+1;j<arr.length;j++){if(arr[i].name==arr[j].name){arr.splice(j,1);//因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j–j--;}}}returnarr;}varnewArr=deWeight();console.log(’%c%s’,‘color:red;’,‘方法一:es5,newArr’,newArr);
方法二:es5新建数据双重循环,去重arr2
vararr2=[{name:‘a’,id:1},{name:‘a’,id:2},{name:‘b’,id:3},{name:‘c’,id:4},{name:‘c’,id:6},{name:‘b’,id:6},{name:‘d’,id:7}];vartemp=[];functiondeWeightTwo(){arr2.forEach(function(a){varcheck=temp.every(function(b){returna.name!==b.name;})check?temp.push(a):’’})returntemp;}varnewArr2=deWeightTwo();console.log(’%c%s’,‘color:red;’,‘方法二:es5,newArr2’,newArr2);
方法三:es6的Map(),去重arr3
vararr3=[{name:‘a’,id:1},{name:‘a’,id:2},{name:‘b’,id:3},{name:‘c’,id:4},{name:‘c’,id:6},{name:‘b’,id:6},{name:‘d’,id:7}];letdeWeightThree=()=>{letmap=newMap();for(letitemofarr3){if(!map.has(item.name)){map.set(item.name,item);}}return[…map.values()];}letnewArr3=deWeightThree();console.log(’%c%s’,‘color:red;’,‘方法三:es6,newArr3’,newArr3);
方法四:es5,对象法去重arr4
vararr4=[{name:‘a’,id:1},{name:‘a’,id:2},{name:‘b’,id:3},{name:‘c’,id:4},{name:‘c’,id:6},{name:‘b’,id:6},{name:‘d’,id:7}];// array.reduce(function(total, currentValue, currentIndex, arr), initialValue)// (function(必选初始值或计算结束返回值, 必选当前元素, 可选索引, 可选原数组),可选函数初始值)varobj={};functiondeWeightFour(){arr4=arr4.reduce(function(a,b){obj[b.name]?’’:obj[b.name]=true&&a.push(b);returna;},[])returnarr4;}varnewArr4=deWeightFour();console.log(’%c%s’,‘color:red;’,‘方法四:es5,newArr4’,newArr4);
原文作者:匆匆那年_海,博客主页:https://www.jianshu.com/u/910c0667c515
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。