admin管理员组

文章数量:1405603

Im stuck on a piece of javascript for the last 4 hours!

The question is how do I count similarities between 2 arrays like so:

arrayA = [a,b,c,d,e,f,g];
arrayB = [c,d,e];

The answer shoud be three. The only piece of code I have at the moment produces a infinite loop :(

Pleas help

Im stuck on a piece of javascript for the last 4 hours!

The question is how do I count similarities between 2 arrays like so:

arrayA = [a,b,c,d,e,f,g];
arrayB = [c,d,e];

The answer shoud be three. The only piece of code I have at the moment produces a infinite loop :(

Pleas help

Share Improve this question edited Nov 13, 2013 at 8:39 geevee 5,4615 gold badges32 silver badges50 bronze badges asked Nov 13, 2013 at 8:23 Bart KlasterBart Klaster 533 silver badges11 bronze badges 1
  • Perhaps you could show the code that produces the infinite loop? – lonesomeday Commented Nov 13, 2013 at 8:27
Add a ment  | 

4 Answers 4

Reset to default 5

One way would be to filter arrayA by checking each to see if it's in arrayB, then getting the length of the new array:

arrayA.filter(function(el) {
    return arrayB.indexOf(el) >= 0;
}).length;

This uses:

  • Array#indexOf
  • Array#filter
  • Array#length

NB that the first two are not available in old browsers, so need to be shimmed using the code in the links given.

here you go (cross browser solution):

[note that .filter() method wont work in IE8 and other old browsers, so i suggest the following approach]

1) define the function:

function count_similarities(arrayA, arrayB) {
    var matches = 0;
    for (i=0;i<arrayA.length;i++) {
        if (arrayB.indexOf(arrayA[i]) != -1)
            matches++;
    }
    return matches;
}

2) call it:

var similarities = count_similarities(arrayA, arrayB);
alert(similarities + ' matches found');

if you don't bother about old browsers support, i'd highly suggest lonesomeday's answer.

hope that helps.

You should take each element of one array and check if it is present in the other using arrayA.indexOf(arrayB[i]) If it doesnt return -1 then increment a count variable. At the end count is your answer.

You can go with $.inArray() function to do this

http://api.jquery./jQuery.inArray/

        $(function () {                    
            arrayA = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
            arrayB = ['c', 'd', 'e'];
            var matchCount = 0;

            $.each(arrayB, function (index, value) {
                if ($.inArray(value, arrayA) != -1)
                    matchCount++;
            });        

            alert("Matched elements : " + matchCount);
       });

本文标签: count similarities between two arrays with javascriptStack Overflow