简体   繁体   中英

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

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.

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
 } 
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM