数组操作

1.去重

   
        function singgleArray(a) {
             var hash = {},
                 len = a.length,
                 result = [];

             for (var i = 0; i < len; i++){
                 if (!hash[a[i]]){
                     hash[a[i]] = true;
                     result.push(a[i]);
                 } 
             }
             return result;
            }

2.去空值

                function trimSpace(array){  
                     for(var i = 0 ;i<array.length;i++)  
                     {  
                         if(array[i] == "" || typeof(array[i]) == "undefined")  
                         {  
                                  array.splice(i,1);  
                                  i= i-1;  
                                
                         }  
                     }  
                     return array;  
                }  

3.取并集

               
                function hebing_array(a,b) {
                    for (var i = 0, j = 0, ci, r = {}, c = []; ci = a[i++] || b[j++]; ) {
                        if (r[ci]) continue;
                        r[ci] = 1;
                        c.push(ci);
                    }
                    return c;
                }

4.取交集

        Array.intersect = function () {
            var result = new Array();
            var obj = {};
            for (var i = 0; i < arguments.length; i++) {
                for (var j = 0; j < arguments[i].length; j++) {
                    var str = arguments[i][j];
                    if (!obj[str]) {
                        obj[str] = 1;
                    }
                    else {
                        obj[str]++;
                        if (obj[str] == arguments.length)
                        {
                            result.push(str);
                        }
                    }//end else
                }//end for j
            }//end for i
            return result;
        }
console.log(Array.intersect(["1", "2", "3"], ["2", "3", "4", "5", "6"]));//[2,3]
 

5.取差集 (2个集合的差集 在arr不存在)

        
        Array.prototype.minus = function (arr) {
            var result = new Array();
            var obj = {};
            for (var i = 0; i < arr.length; i++) {
                obj[arr[i]] = 1;
            }
            for (var j = 0; j < this.length; j++) {
                if (!obj[this[j]])
                {
                    obj[this[j]] = 1;
                    result.push(this[j]);
                }
            }
            return result;
        };
   
        console.log(["2", "3", "4", "5", "6"].minus(["1", "2", "3"]));

部分参考:https://www.cnblogs.com/majiang/p/5910224.html

posted @ 2017-11-23 14:22  Rainyn  阅读(128)  评论(0编辑  收藏  举报