开发者

Javascript compare two arrays of variable length and show if there's common elment(s) [duplicate]

This question already has answers here: Cl开发者_Go百科osed 10 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜