4

I am trying to learn how to compare two values between arrays with corresponding index. Like

var A = [2,12,3,42];
var B = [12,42,44,12];

So i know i need to loop in these arrays, but how do i compare two values based on index?

Like, index of [0] from A to compare with index of [0] from B, etc?

Bokchee 88
  • 267
  • 1
  • 6
  • 18
  • 2
    Possible duplicate of [How to compare arrays in JavaScript?](http://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Rajesh Oct 22 '16 at 14:15

2 Answers2

3

You will have to loop over arrays and compare every element.

Considering, there can be arrays of different length, you should take max of them and check. Under such circumstances, if length of A is 4 and you try to access A[4] this will return undefined.

var A = [2, 12, 3, 42];
var B = [12, 42, 44, 12, 123];

var len = Math.max(A.length, B.length);
console.log(len)
for (var i = 0; i < len; i++) {
  console.log(A[i], B[i], A[i] === B[i])
}
Rajesh
  • 24,354
  • 5
  • 48
  • 79
2
var firstElementEqual = A[0] === B[0]

This should be everything you need to do. You can simply reference the values by using the index and then comparing it like it's a normal variable.

Example:

var A = [2,12,3,42];
var B = [12,42,44,12];

console.log(A[0] === B[0]); // This will return false, as 2 A[0] is not equal to 12 B[0]
Ivan Sieder
  • 934
  • 1
  • 10
  • 24
  • This did in fact answer the question. The OP did not ask to compare the entire arrays, but just two values given a specific index. – Eric Majerus Feb 04 '17 at 06:42