比较两个数组,如果两个数组中至少有一个,则返回true [duplicate]

时间:2023-01-20 12:11:42

This question already has an answer here:

这个问题在这里已有答案:

I am writing an ionic app - so this is in angular 1.x

我正在写一个离子应用程序 - 所以这是角度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.

阵列32中有两个公共数字,64。

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

如果2个阵列中至少有1个公共号码,我只想要一些javascript有效地返回true。

I have the following code

我有以下代码

angular.forEach(arr1 , function (arr1 , count) {
              if ( inArray(arr1 , arr2) )
              {
                return true;
              }
          });

3 个解决方案

#1


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));

#2


2  

This is trivial to do with ES6:

这对于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)));

#3


0  

  • MDN some - stops looking when it finds a match, returns boolean
  • MDN一些 - 当找到匹配时停止查找,返回布尔值
  • MDN includes - returns boolean to state if item is in array
  • MDN包括 - 如果item在数组中,则返回boolean to state

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);

#1


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));

#2


2  

This is trivial to do with ES6:

这对于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)));

#3


0  

  • MDN some - stops looking when it finds a match, returns boolean
  • MDN一些 - 当找到匹配时停止查找,返回布尔值
  • MDN includes - returns boolean to state if item is in array
  • MDN包括 - 如果item在数组中,则返回boolean to state

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);