js数组去重,合集等操作

<html>
<head>

<script type="text/javascript">
var a=['a','b','c'];
var b=['a','b','d','f'];
var arr1 = intersection(a,b);
alert("a,b的合集-不重复:"+arr1);
var arr2 = chaji(a,b);
alert("a与b不重复的部分:"+arr2);
var arr3 = inANotInB(a,b);
alert("b与a不重复的部分:"+arr3);

//a,b合集
function intersection(a,b){
  var obj = new Object();
  for(var i =0,len = a.length;i<len;i++){
    obj[a[i]] = a[i];
  }
  for(var i =0,len = b.length;i<len;i++){
    obj[b[i]] = b[i];
  }
  var arr = new Array();
  var i = 0; 
  for(var per in obj){
    arr[i++] = obj[per];
  }
  return arr;
}

//a与b不重复的部分
function chaji(a,b){
   var obj = new Object();
  for(var i =0,len = a.length;i<len;i++){
    obj[a[i]] = 1;
  }
  for(var i =0,len = b.length;i<len;i++){
    obj[b[i]] = obj[b[i]]?2:1;
  }
  var arr = new Array();
  var i = 0; 
  for(var per in obj){
    if(obj[per] == 1){
      arr[i++] = per;
    }
  }
  return arr;
}

//b与a不重复的部分
function inANotInB(a,b){
    var obj = new Object();
    for(var i =0,len = a.length;i<len;i++){
        obj[a[i]] = 1;
    }
    for(var i =0,len = b.length;i<len;i++){
        if(obj.hasOwnProperty(b[i])){
            obj[b[i]] = undefined;
        }
    }
    var arr = new Array();
    var i = 0; 
    for(var per in obj){
        if(obj[per]){
            arr[i++] = per;
        }
    }
    return arr;
}

</script>
</head>
</html> 

  

posted @ 2012-03-12 14:17  cyjch  阅读(1384)  评论(0编辑  收藏  举报