By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
460,036 Members | 960 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 460,036 IT Pros & Developers. It's quick & easy.

Question about array

P: 15
In php, we have array_intersect to check if 2 arrays have intersected. Is there anythings like that in Javascript??
Sep 20 '08 #1
Share this Question
Share on Google+
4 Replies


Dormilich
Expert Mod 5K+
P: 8,639
nope, but maybe one of the "callback methods" may solve this for you.

regards
Sep 20 '08 #2

P: 15
Thanks very much, i will check that in details.
Sep 20 '08 #3

rnd me
Expert 100+
P: 427
Expand|Select|Wrap|Line Numbers
  1.  
  2. if (!Array.prototype.indexOf) {Array.prototype.indexOf = function (obj) { var mx=this.length;
  3. for (var i = 0; i <mx; i++) {if (this[i] === obj) {return i;}}return -1;};}
  4.  
  5. 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;}
  6.  
Sep 21 '08 #4

rnd me
Expert 100+
P: 427
here is more legible code:
[PHP]


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.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]
Sep 21 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.