Question about array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wesley1970
    New Member
    • Nov 2007
    • 15

    Question about array

    In php, we have array_intersect to check if 2 arrays have intersected. Is there anythings like that in Javascript??
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    nope, but maybe one of the "callback methods" may solve this for you.

    regards

    Comment

    • wesley1970
      New Member
      • Nov 2007
      • 15

      #3
      Thanks very much, i will check that in details.

      Comment

      • rnd me
        Recognized Expert Contributor
        • Jun 2007
        • 427

        #4
        Code:
        if (!Array.prototype.indexOf) {Array.prototype.indexOf = function (obj) { var mx=this.length;
        for (var i = 0; i <mx; i++) {if (this[i] === obj) {return i;}}return -1;};}
        
        Array.prototype.intersection = function (r) {var mx = Math.min(this.length, r.length), t = [], i = 0;for (z = 0; z < mx; z++) {if (r.indexOf(this[z]) > -1) {t[i++] = this[z];}}return t;}

        Comment

        • rnd me
          Recognized Expert Contributor
          • Jun 2007
          • 427

          #5
          here is more legible code:
          [PHP]


          if (!Array.prototy pe.indexOf) {
          Array.prototype .indexOf = function (obj) {
          var mx = this.length;
          for (var i = 0; i < mx; i++) {
          if (this[i] === obj) {
          return i;
          }
          }
          return -1;
          }
          }


          Array.prototype .intersect = function (r) {
          var mx = this.length, t = [], z = 0, i = 0;
          for (z = 0; z < mx; z++) {
          if (r.indexOf(this[z]) > -1) {
          t[i++] = this[z];
          }
          }
          return t;
          }
          [/PHP]



          it takes two functions: one to make matches, and another to collect.


          usage example:
          [PHP]
          var days = [ 0,1,2,3,4,5,6 ];
          var months = [ 1,2,3,4,5,6,7,8 ,9,10,11,12 ];
          var both = days.intersect( months )
          alert( both ); // shows: 1,2,3,4,5,6

          [/PHP]

          Comment

          Working...