Array.prototype.unique=function(){// s为hash表,r为临时数组var s ={}, r =[];for(var i =0; i <this.length; i++){// 如果hash表中没有当前项if(!s[this[i]]){// 存入hash表[this[i]]=true;// 把当前数组的当前项push到临时数组里面
r.push(this[i]);}}return r;}
先排序,后比较
Array.prototype.unique=function(){this.sort();var s =[this[0]];for(var i =1; i <this.length; i++){if(this[i]!== s[s.length -1]){
s.push(this[i]);}}return s;}
数组存放,indexOf()判断(支持ie6-8)
Array.prototype.unique=function(){var n =[];// 存放已遍历的满足条件的元素for(var i =0; i <this.length; i++){// indexOf()判断当前元素是否已存在if(n.indexOf(this[i])==-1) n.push(this[i]);}return n;}
过滤去重
var arr =['apple','strawberry','banana','pear','apple','orange','orange','strawberry'];var r = arr.filter(function(element, index, self){return self.indexOf(element)=== index;});