0

I don't want to compare the two arrays as a whole, I specifically want to check if the 2nd array has any values that match a value in the first one. I then want to return the value that matches in both.

If I'm not mistaken, comparing two arrays as a whole would be done like this:

array1 = [1,2,3];
array2 = [1,3,4];

console.log(JSON.encode(array1)==JSON.encode(array2));

So in this case, I would want to check if array2 has any matching values to array one, not if they both are equivalent. Any help is appreciated!

KoftaClarence
  • 125
  • 1
  • 2
  • 11

1 Answers1

0
var array1 = [1, 2, 3],
    array2 = [1, 3, 4];

var AnyItemsOfArray1InArray2 = array1.some(function(item) {
    return array2.indexOf(item) > -1;
});
console.log(AnyItemsOfArray1InArray2);

var ItemsOfArray1InArray2 = array1.filter(function(item) {
    return array2.indexOf(item) > -1;
});
console.log(ItemsOfArray1InArray2);
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • Thanks! If you don't mind, could you explain what's going in in each part? – KoftaClarence Mar 30 '14 at 15:11
  • Have a look at the documentation of [`.some()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) and [`.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – Andreas Mar 30 '14 at 17:41