I have 2 arrays that I need to compare against each other and retun the count of the same:

ex: array1[abcd] array2 [adce] return would be 2 as both a and c are in same postion.

I would then have to return 2,1 as a and c are in the same place but d is in the array but in the wrong place.

     var  index = 0;

     for(index = 0; index < length; index++){
     if(array1[index] == array2[index]){
     count++
    } 

return count
}

which i ofcourse is only returning 1, so not sure where to go from here?

Recommended Answers

All 5 Replies

you're missing a brace so the for loop will always return on the first iteration.

    for(index = 0; index < length; index++){
        if(array1[index] == array2[index]){
            count++
        }
    } //<-- add this brace and see if that fixes it.
    return count
}
commented: thank you for your help +0

Sorry I just missed it out in the example, but have it in, so that doesn't seem to be the problem.
I am thinking that it has to do with my for() index< lenght; as it is returning 1, which tells me that it is saying the length is the same. I could be wrong , I am new to javascript. So what I need it to do is compare individual elements and return those counts.... number for correct and number for correct and in wrong place. Does this make sense?

the comparison you have should tell you the exact matches (though you are missing ;'s off the end of lines 5 & 8 (javascrip is a little forgiving if its the last line in a block).

You will have to have a nested loop to do the "correct but in wrong place" check.

Are you able to post any more code, the snippet posted above is obviously only a portion and it would be easier to help spot the issue if you can provide the whole function.

Thank you Hearth, you are right, once I fixed it up, it worked jsut the way I wanted it to. Thanks you :)

Great! No worries, glad I could help. Can you make this thread as solved please? thx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.