1

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

Community
  • 1
  • 1
Nomad
  • 1,092
  • 11
  • 29
  • 42

2 Answers2

3

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
        }
    }
}
hugomg
  • 68,213
  • 24
  • 160
  • 246
0

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.

qw3n
  • 6,236
  • 6
  • 33
  • 62