In php, we have array_intersect to check if 2 arrays have intersected. Is there anythings like that in Javascript??
Question about array
Collapse
X
-
Tags: None
-
-
-
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
-
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
Comment