Nodejs Array Intersect intersect(ar)

Here you can find the source of intersect(ar)

Method Source Code

Array.prototype.intersect = function(ar) {
   var results = [];
   for (var i = 0, len = this.length; i < len; i++) {
      for (var j = 0, len2 = ar.length; j < len2; j++) {
         if (this[i] === ar[j]) {
            var found = false;
            for (var k = 0, len3 = results.length; k < len3; k++) {
               if (ar[j] === results[k]) {
                  found = true;/*from   www  . jav  a 2  s . c om*/
                  break;
               }
            }
            if (!found) {
               results.push(ar[j]);
            }
         }
      }
   }
   
   return results;
};

// refactored
Array.prototype.intersect = function(ar) {
   var results = [], uniq = this.uniq();
   for (var i = 0, len = uniq.length; i < len; i++) {
      for (var j = 0, len2 = ar.length; j < len2; j++) {
         if (uniq[i] === ar[j]) {
            results.push(ar[j]);
         }
      }
   }
   
   return results;
};

// refactored
Array.prototype.intersect = function(ar) {
   var results = [], uniq = this.uniq();
   for (var i = 0, len = uniq.length; i < len; i++) {
      if (ar.indexOf(uniq[i]) >= 0) {
         results.push(uniq[i]);
      }
   }
   
   return results;
};

// refactored (requires Enumerable)
Array.prototype.intersect = function(ar) {
   return this.uniq().findAll(function(elem) {
      return ar.detect(function(value) {
         return elem === value;
      });
   });
};

Related

  1. intersect
    Array.prototype.intersect =
      function(otherArray) [ i for each( i in this ) if( otherArray.has( i ) ) ];
    
  2. intersect(a)
    Array.prototype.intersect = function(a) {
        return this.filter(function(x) {
      return a.indexOf(x) >= 0;
        });
    
  3. intersect(a, b)
    Array.intersect = function(a, b){
         return a.uniquelize().each(function(o){return b.contains(o) ? o : null});
    };
    
  4. intersect(arr)
    Array.prototype.intersect = function (arr) {
      return this.filter(function (el, idx) {
        return arr.indexOf(el) >= 0;
      }).unique();
    };
    
  5. intersect(arr, comparer)
    Array.prototype.intersect = function (arr, comparer) {
      comparer = comparer || EqualityComparer;
      return this.distinct(comparer).where(function (t) {
        return arr.contains(t, comparer);
      });
    };
    
  6. intersect(array)
    Array.prototype.intersect = function (array) {
        array = Array.isArray(array) ? array : [];
        return this.filter(function (n) {
            return array.indexOf(n) != -1;
        });
    };
    
  7. intersect(array)
    Array.prototype.intersect = function(array){
      return(this.filter(function(n){ return array.include(n); }));
    };