Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript How to compare values between two arrays?

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?

like image 667
Bokchee 88 Avatar asked Oct 18 '25 06:10

Bokchee 88


1 Answers

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])
}
like image 58
Rajesh Avatar answered Oct 20 '25 05:10

Rajesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!