# 数组去重问题

xiaoxiao2021-03-01  8

function uniq(array) { var map={}; var re=[]; for(var i=0,l=array.length;i<l;i++) { if(typeof map[array[i]] == "undefined"){ map[array[i]]=1; re.push(array[i]); } } return re; }

uniq([1,2,1,2,4]);

uniq([{x:1},"[object Object]"]); uniq([{x:1},{z:2}]);

HashMap In Java :

class Holder { int i; } public class Test3 { /** * @param args */ public static void main(String[] args) { HashMap<Holder, Holder> map=new HashMap<Holder, Holder>(); Holder key= new Holder(); Holder value= new Holder(); value.i=1; map.put(key, value); Holder key2=new Holder(); System.out.println(map.get(key).i); System.out.println(map.get(key2)); } }

Object In Javascript:

var x={}; var y={ toString:function(){ return "z"; } }; x[y]=1; alert(x["z"]);

/** *unique the array *@param {Array} array array to unique *@return {Array} uniqued array ,note change parameter */ function undulpicate(array){ for(var i=0;i<array.length;i++) { for(var j=i+1;j<array.length;j++) { //注意 === if(array[i]===array[j]) { array.splice(j,1); j--; } } } return array; }

ps: Jquery Uniq Node

var x={z:1}; var y={q:2}; function uniqObjects(array){ var re=[]; for(var i=0,l=array.length;i<l;i++) { if(typeof array[i]["_uniqObjects"] == "undefined"){ //添加标签 array[i]["_uniqObjects"]=1; re.push(array[i]); } } //取出标签 for(var i=0,l=re.length;i<l;i++) { delete re[i]["_uniqObjects"]; } return re; } uniqObjects([x,y,x]);

unique: function( array ) { var ret = [], done = {}; try { for ( var i = 0, length = array.length; i < length; i++ ) { var id = jQuery.data( array[ i ] ); if ( !done[ id ] ) { done[ id ] = true; ret.push( array[ i ] ); } } } catch( e ) { ret = array; } return ret; },