Home > OS >  How to check if two elements inside two array have the same index?
How to check if two elements inside two array have the same index?

Time:12-12

I am new to javascript and want to know if there is a possible method to find out if an element inside an array has the same index as another element inside another array.

For example :

var a = [4,6,3]
var b = [6,6,0]

how can I find out if the elements at index 1 in both arrays are the same in Javascript or using jQuery?

I cannot figure this and and any help would be deeply appreciated.

CodePudding user response:

Before learning those easy-to-use methods, I'm personally think you should learn to solve it in a very basic way first

let index = -1; // -1 normally defined as not found

for (let i = 0 ; i < a.length ; i  ) {
 for (let j = 0 ; j < b.length ; j  ) {
  if (a[i] === b[j]) {
   index = i; // or index = j; is the same
  } // we won't need else since we don't need to do anything when the numbers are not match
 } 
}

CodePudding user response:

Since you asked for the "magical" JS way,

a.some((i,j) => i == b[j]) should do what you're asking.

The some command runs a function across every element of the array and checks if any of them are true. The function parameters i is the value of the elements in the first array and j is the index. We use the j to get the value of b at that point and check if it's equal.

  • Related