I have 2 arrays that I need to compare against each other and return the count of the same.
Example: compare array1 [abcd] against array2 [adce]. Return would be 2,1 as both a and c are in same position and d is in the wrong position.
function () {
var index = 0;
for (index = 0; index < length; index++) {
if (array1[index] == array2[index]) {
count++
}
}
return count
}
I'm getting a return of 1. I think that's because they equal in length that is why I'm getting a 1. So I'm thinking that I now need to put another for
loop and have that loop go through the elements individually, but not sure how to do this. I could be completely wrong in what I have put above, if so, could someone explain the process to me please.
There is a JS library UnderscoreJS which provides a number of useful method for processing JavaScript arrays. You can use its difference method:
You get
1
as output becauselength
is not defined in your codeDemo Fiddle : http://jsfiddle.net/tCKE7/2/
If I interpret correctly, you want to find a count of elements that are at the same, exact position and a count of elements that are present in both arrays but not at the same position.
This isn't a rock-solid approach and would not work for duplicates.
Array.indexOf
Fiddle: Fiddle