日期:2014-05-16  浏览次数:20392 次

JS去除重复数据

 <script language="JavaScript">
  <!--
	Array.prototype.distinct = function(field) {  
  var set = {},  
    hasField = typeof(field)!='undefined';  
  for(var i=this.length-1; i>=0; i--){  
    var obj = this[i],  
      cacheKey = hasField ? obj[field] : obj;  
    if(cacheKey in set){  
      this.splice(i, 1);  
      continue;  
    }else{  
      set[cacheKey] = null;  
    }  
  }  
}  
  
//test  
var a = [{id:1, name:'aaa'}, {id:2, name:'bbb'}, {id:1, name:'ccc'}];  
a.distinct('id');  
  
var b = [1,2,3,'a','b',2,'b',3];  
b.distinct();  
  
alert(a);  
alert(b);
  //-->
  </script>


说明:此实例数组类型为
var values =new Object();
values.id= getValues[i].id;
values.text= getValues[i].text;
values.checked="1";

所以:判断条件为  if (this[i].id === this[j].id)
如果数据类型为
var s = [1,2,3····n];
则,修改为
if (this[i] === this[j])
即可!