0

I have 2 arrays, for example:

Array1: [One, Two, Three, Four, Five] Array2: [Three, Five]

I need to have a function which returns true if any values in Array2 match any values in Array1.

I have tried:

var compareArray = $.inArray(Array1, Array2);

but this always returns '-1'.

Horizon_Net
  • 5,959
  • 4
  • 31
  • 34
Matt Price
  • 1,371
  • 2
  • 9
  • 19
  • That's because the $.inArray() function takes a value and an Array. Not an entire Array and the other array. So, you'd have to loop through the Array (using a for loop) to pass each value to compare against the other array. – 3abqari Jun 20 '15 at 14:54
  • OK how would i loop through an array and compare each value with the other array? thanks – Matt Price Jun 20 '15 at 14:58

2 Answers2

0

Here is another questions that you can use as a guide to your solution:

Comparing two arrays in jquery

Community
  • 1
  • 1
3abqari
  • 228
  • 1
  • 2
  • 10
0

You could try a brute force algorithm if you are only working with small arrays. Something like the following should work.

function findMatch(arr1, arr2) {
  for (i=0; i < arr1.length; i++) {
    for (j=0; j < arr2.length; j++) {
      if (arr1[i] === arr2[j]) {
        return true
      }
    }
  }
  
  return false
}
Rose R.
  • 141
  • 11