Javascript compare two arrays of variable length and show if there's common elment(s) [duplicate]
Possible Duplicate:
Simplest code for array intersection in javascript
I want to compare two arrays of different length and if there's a common element between them show an alert or dosomething.
var valuesAdded= ["ab","c","d","eeef","bbc","ac","jk","df","ss"]
var valuesToadd= ["aaa","jk","eeef","ddd","d","ab","rs"]
so either valuesAdded can be larger or valuesToadd can be larger, but what i want is compare them for those element that already exists in the above case "eeef","d","jk","ab" and show an alert that these are already in valuesAdded etc.
I would like to do in regular javascript or usingdojo.
Can you please help in this regards, your help will be appreciated.
Thanks
Nothing really Javascript specific here:
for(var i = 0; i<arr1.length; i++){
for(var j=0; j<arr2.length; j++){
if(arr1[i] === arr2[j]){
//do something
}
}
}
For modern browsers you can do
valuesToAdd.forEach(){function(a){
valuesAdded.indexOf+1?valuesAdded.push(a):alert('You already have this item');
}};
For older browser less than IE9 you would have to fall back to the other methods presented here.
精彩评论