Bart Klaster
Bart Klaster

Reputation: 53

count similarities between two arrays with javascript

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

Upvotes: 2

Views: 4283

Answers (4)

Shyam Shinde
Shyam Shinde

Reputation: 299

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

http://api.jquery.com/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);
       });

Upvotes: -2

geevee
geevee

Reputation: 5451

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.

Upvotes: 4

lonesomeday
lonesomeday

Reputation: 237845

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:

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

Upvotes: 5

nette
nette

Reputation: 575

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.

Upvotes: 0

Related Questions