两个数组取交集、差集和数组去重的方法

两个数组取差集

<script>
    var alpha = [1, 2, 3, 4, 5, 6],
    beta = [4, 5, 6, 7, 8, 9];

    $.arrayIntersect = function(a, b)
    {
        return $.merge($.grep(a, function(i)
            {
                return $.inArray(i, b) == -1;
            }) , $.grep(b, function(i)
            {
                return $.inArray(i, a) == -1;
            })
        );
    };

    window.console && console.log( $.arrayIntersect(alpha, beta) );
</script>

两个取交集

<script>
$(function(){
        function arrayIntersection(a, b)
        {
          var ai=0, bi=0;
          var result = new Array();
         
          while( ai < a.length && bi < b.length )
          {
             if      (a[ai] < b[bi] ){ ai++; }
             else if (a[ai] > b[bi] ){ bi++; }
             else /* they're equal */
             {
               result.push(a[ai]);
               ai++;
               bi++;
             }
          }
         
          return result;
        }
         
        console.log(arrayIntersection([1,2,3],[2,3,4,5,6]));//[2,3]
    })
</script>

数组去重的方法

$(function(){
        var arr = [0,2,4,2,1,0];
        var new_arr = [];
        for(var i = 0;i<arr.length;i++){
            var items = arr[i];
            if($.inArray(items,new_arr)==-1){
                new_arr.push(items);
            }
        }
    })

 

posted @ 2016-12-02 16:06  欢欢_blog  阅读(1759)  评论(0编辑  收藏  举报