2

1、数组取差

    //es6
    arryMinus (arry1,arry2){
        let a = new Set(arry1);
        let b = new Set(arry2);
        let difference = new Set([...a].filter(x => !b.has(x)));
        return Array.from(difference);
    }
    //循环
    arryMinus (arry1,arry2){
        var arr3 = new Array();
        for(var i=0; i < arry1.length; i++){
            var flag = true;
           for(var j=0; j < arry2.length; j++){
                 if(arry1[i] == arry2[j]) {
                   flag = false;
                 }
        
             }
           if(flag){
                 arr3.push(arry1[i]);
           }
       }
       return arr3;

       
    }

2、数组取交集

     //es6
    arryIntersect (arr1,arr2){
        // 利用set方法取交集
        let a = new Set(arr1);
        let b = new Set(arr2);

        let intersect = new Set([...a].filter(x => b.has(x)));
        return Array.from(intersect);
     }
    
    arryIntersect (arr1,arr2){
     //循环判断数组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;
    }

3、数组去重

     //es6
    arryUnique (array){
        // 去除数组的重复成员
        return [...new Set(array)]
    }
      arryUnique (array){
        var res = [];
        var json = {};
        for(var i = 0; i < this.length; i++){
            if(!json[this[i]]){
                res.push(this[i]);
                json[this[i]] = 1;
            }
        }
        return res;
    }

二维数组转一维数组

  // 二维数组转为一维数组
    twoArrToOneArr(arr){
        return [].concat.apply([],arr);
    }

weijie
164 声望7 粉丝