详解JavaScript数组和字符串中去除重复值的方法
原理在代码中表现得非常清晰,我们直接来看代码例子:
varages=array.map(function(obj){returnobj.age;}); ages=ages.filter(function(v,i){returnages.indexOf(v)==i;}); console.log(ages);//=>[17,35]
functionisBigEnough(element){ returnelement>=10; } varfiltered=[12,5,8,130,44].filter(isBigEnough); //filteredis[12,130,44]
functiononlyUnique(value,index,self){ returnself.indexOf(value)===index; } //usageexample: vara=['a',1,'a',2,'1']; varunique=a.filter(onlyUnique);//returns['a',1,2,'1']
比较好使的Function(不兼容IE7)
functionunique(array){ returnarray.filter(function(el,index,arr){ returnindex==arr.indexOf(el); }); }
比较好使的Function(兼容IE7)
//去除数组中重复值 functiongetNoRepeat(s){ returns.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(","); } vararr=["北京","上海","天津","武汉","上海","天津","武汉","北京","上海","天津","武汉","天津","武汉","天津","武汉","天津","武汉", "北京","上海","天津","武汉","上海","天津","武汉","北京","上海","天津","武汉","天津","武汉","天津","武汉","天津","武汉", "北京","上海","天津","武汉","上海","天津","武汉","北京","上海","天津","武汉","天津","武汉","天津","武汉","天津","武汉"]; arr=getNoRepeat(arr); alert(arr.length);//4 alert(arr.toString());//"北京","上海","天津","武汉"
利用map原理
vararr=["北京","上海","天津","武汉","上海","天津","武汉","北京","上海","天津","武汉","天津","武汉","天津","武汉","天津","武汉", "北京","上海","天津","武汉","上海","天津","武汉","北京","上海","天津","武汉","天津","武汉","天津","武汉","天津","武汉", "北京","上海","天津","武汉","上海","天津","武汉","北京","上海","天津","武汉","天津","武汉","天津","武汉","天津","武汉"]; varjson={}; for(vari=0;i<arr.length;i++){ json[arr[i]]=arr[i]; } arr=newArray(); for(varkeyinjson){ arr.push(key); } alert(arr.toString()); //"北京","上海","天津","武汉"