...

View Full Version : compare arrays



alcool9999
06-12-2010, 04:53 PM
hi i have two arrays and i need to know which strings are in both arrays.

i know how to do the bit if the string is in both but i don't know how to compare them as such.

thanks

mrhoo
06-12-2010, 05:53 PM
Most modern browsers extend Arrays with some common useful methods-
filter(function) returns an array containing the members that pass a test or condition,
and indexOf(value) returns the first element that matches its argument, or -1, if no instance is found.

To extend support for these to IE and other older clients you can
add them if they are not defined.



if(![].filter){
Array.prototype.filter= function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
}
}
if(![].indexOf){
Array.prototype.indexOf= function(what, i){
i= i || 0;
var L= this.length;
while(i< L){
if(this[i]=== what) return i;
++i;
}
return -1;
}
}
var arr1= [1, 2, 3, 4, 5, 6, 7, 8, 9],
arr2= [2, 4, 6, 8, 10, 12, 14, 16, 18];

var shared=arr1.filter(function(itm){
return arr2.indexOf(itm)!= -1
});

alert('shared='+shared)

/* returned value: (String)
shared=2,4,6,8



If you need to repeatedly compare arrays you can add your own method-


Array.prototype.common= function(ar){
return this.filter(function(itm){
return ar.indexOf(itm)!= -1;
});
}

var shared=arr1.common(arr2);
*/

alcool9999
06-12-2010, 05:55 PM
ok great thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum