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
2
  • 3
    Do it the same way as You do it as a human - go element by element in both arrays and compare them. Where is the problem? Commented Nov 9, 2015 at 10:42
  • 1
    array1.filter(function(v, i) {return v === array2[i];}).length; Commented Nov 9, 2015 at 10:43

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

Comments

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>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.