0

I am searching for a function which compare how much values match in an array. It should be sequence dependent. That mean i.e. the first object in the first array should be compared to equality to the first object in the second array and so on. I actually looked at this, but there become only the length compared and the length is in my case always the same. The possibly objects in the array are 1,2,3,4,5,6,7,8,9. Should I split the arrays and compare them then and when yes how?

Here are two examples:

var array1 = ["3","4","2"];
var array2 = ["9","4","7"];
// result = 1

second example:

var array1 = ["9","4","7","3"];
var array2 = ["3","4","7","2"];
// result = 2
Community
  • 1
  • 1
Bodoppels
  • 406
  • 7
  • 24

2 Answers2

5

Try this

var array1 = ["3","4","2"];
var array2 = ["9","4","7"];

function equal(array1, array2) {
  var len = array1.length, i, count = 0;
  
  for (i = 0; i < len; i++) {
    if (array1[i] === array2[i]) {
      count++;
    }
  }
  
  return count;
}

console.log(equal(array1, array2));
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
0

Solution which iterates over the items and count the equal elements.

function compare(a1, a2) {
    var i = 0, count = 0;
    while (i < a1.length && i < a2.length) {
        a1[i] === a2[i] && count++;
        i++;
    }
    return count;
}

document.write(compare(["3", "4", "2"], ["9", "4", "7"]) + '<br>');
document.write(compare(["9", "4", "7", "3"], ["3", "4", "7", "2"]) + '<br>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392