0

I am writing an Ionic app - so this is in Angular 1.x

I have two arrays of numbers:

var arr1 = [1,32,423,43,23,64,232,5,67,54];
var arr2 = [11,32,1423,143,123,64,2232,35,467,594];

There are two common numbers in the array 32, and 64.

I want some JavaScript to efficiently return true if there is at least 1 common number in the 2 arrays.

I have the following code

angular.forEach(arr1 , function (arr1 , count) {
      if ( inArray(arr1 , arr2) )
      {
        return true;
      }
  });
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
GMan
  • 444
  • 1
  • 11
  • 24
  • You don't need to used Angular or any library for that matter. Simple filter the larger array against the smaller one... https://jsfiddle.net/MrPolywhirl/n4022zoz/ – Mr. Polywhirl Nov 16 '16 at 13:27

3 Answers3

6

This is trivial to do with ES6:

var arr1 = [1, 32, 423, 43, 23, 64, 232, 5, 67, 54];
var arr2 = [11, 32, 1423, 143, 123, 64, 2232, 35, 467, 594];

console.log(arr1.some(i => arr2.includes(i)));
Jonathan
  • 8,771
  • 4
  • 41
  • 78
2

var arr1 = [1, 32, 423, 43, 23, 64, 232, 5, 67, 54];
var arr2 = [11, 32, 1423, 143, 123, 64, 2232, 35, 467, 594];

function hasCommonNumbers(arr1, arr2) {
  let found = false;
  for (let i = 0; i < arr1.length; i++) {
    if (arr2.indexOf(arr1[i]) !== -1) {
      found = true;
      break;
    }
  }
  return found;
}

console.log(hasCommonNumbers(arr1,arr2));
Weedoze
  • 13,683
  • 1
  • 33
  • 63
0
  • MDN some - stops looking when it finds a match, returns boolean
  • MDN includes - returns boolean to state if item is in array

var arr1 = [1,32,423,43,23,64,232,5,67,54];
var arr2 = [11,32,1423,143,123,64,2232,35,467,594];

var hasDupe = arr1.some(function(val){
   return arr2.includes(val);
});

console.log(hasDupe);
epascarello
  • 204,599
  • 20
  • 195
  • 236