使用js完成前端集合运算

要求是这样的:有组员和组两个集合,组员可以属于多个组;然后求多个组员所属的组别的交集;

假设集合的关系如下:

使用js完成前端集合运算

那么对于组员的集合来说:记录其id为customers_id(从0开始递增),对于组来说:记录其id为gruops_id(从0开始递增)就可以定义为一个数组:

var customers = [{"customers_id":1,"group_ids": [1,2,3]} , {"customers_id":2,"group_ids":[1,2,3,4]}, {"customers_id":3,"group_ids":[3,4,5,6]},{"customers_id":3,"group_ids":[3,5]}];

var groups = [1,2,3,4,5,6];

那么求出customers的groups_id中的共同的元素,即是:组员所属的组别的交集;

我的思路:将customers中的groups_id合并去重,将记录放到哈希表(关于哈希表参看数据结构相关书籍或者:http://www.cnblogs.com/super-d2/archive/2012/08/04/2620800.html)的key中,将记录个数字放到哈希表的value中;若其中key对于的value值等于customers.length则,标记为共有集合;

具体实现算法如下:

<script language="javascript">

var customers = [{"customers_id":1,"group_ids": [1,2,3]} , {"customers_id":2,"group_ids":[1,2,3,4]}, {"customers_id":3,"group_ids":[3,4,5,6]},{"customers_id":3,"group_ids":[3,5]}];

    

    var arr = new Array();



    for(var i = 0; i < customers.length ; i++){

        arr = arr.concat(customers[i].group_ids);

    }



    var new_arr = delRepeat(arr);



    var hashCompany = new Hashtable();

    

    for(var i = 0; i < new_arr.length; i++){

        hashCompany.add(new_arr[i],count(arr, new_arr[i]));

    }

    

    var mark = [];



    for(var i = 0; i < new_arr.length; i++){

        if(hashCompany.items(new_arr[i]) == customers.length){

            //=>把要标识的存储到集合里 

            mark.push(new_arr[i]);

        }

    }



    function count(arr, value) {

        var count = 0;

        for ( var i in arr) {

            if (arr[i] == value)

                count++;

        }

        return count;

    }

    

     function delRepeat(arr){

        var newArray = new Array();

          var len = arr.length;

        for(var i=0;i<len;i++){

                 for(var j=i+1 ; j<len ; j++){

                       if(arr[i] == arr[j]){

                    ++i;

                       }

            }

                newArray.push(arr[i]);

          }

         return newArray;

    } 



     function Hashtable(){ 

        this._hash = {}; //key:value,原生(浏览器或者解析引擎)已经实现了hashTable

        this._count = 0; 

         this.add = function(key, value){ 

                if (this._hash.hasOwnProperty(key)) return false; 

                 else { this._hash[key] = value; this._count++; return true; } 

         } 

         this.remove = function(key) { delete this._hash[key]; this._count--; } 

          this.count = function() { return this._count; } 

          this.items = function(key) { if (this.contains(key)) return this._hash[key]; } 

         this.contains = function(key) { return this._hash.hasOwnProperty(key); } 

        this.clear = function() { this._hash = {}; this._count = 0; } 

    }



</script>

最后得到的mark为公共组的集合。

 

 

你可能感兴趣的:(js)