Common methods of collection in js

 

//-------The method of taking the intersection of two arrays---------
Array.ExistsSameValues = function(a1, a2) {
    var exists = false;
    if(a1 instanceof Array && a2 instanceof Array)
    {
        for  ( var  i = 0 , iLen =a1. lengthi < iLeni ++)
        {
            for (var j=0,jLen=a2.lengthj<jLenj++)
            {
                if (a1[i]===a2[j])
                {
                    return true;
                }
            }
        }
    }
    return exists;
};
//Instructions for use, a set is a complete set b is a subset such as a=[1,2,3,4,5] b=[1,2,3]
function getNotSame(a,b){
 var c = [];
 var tmp = a.concat(b);
 var o={};
 for(var i = 0; i<tmp.length; i++) (tmp[i] in o) ? o[tmp[i]] ++ :o[tmp[i]] = 1;
 for(x in o) if(o[x] == 1) c.push(x);
 return c;
}

 

/**
 * Find the largest element in an array
 * @param tmp Array
 * @returns {max}
 */
 function getMax (tmp) {
      var max = tmp[ 0 ];
      for ( var i = 1 ; i < tmp. length ; i ++) {
          if ( max < tmp[ i ]) {
              max = tmp[ i ];
         }
     }
     return max;
 }

 

//Determine whether set a really contains set b
 function checkAcontainB (a, b) {
     var ai = 0 , bi = 0 ;
     // intersection of sets a and b
 var c = 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 */{
            c.push(a[ai]);
            ai++;
            bi++;
        }
    }
    if (c.length < b.length) {
        return false;
    } else {
        return true;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326721379&siteId=291194637