Technicalarticles

3种方法快速查找两个数组是否在Javascript中包含任何公共项
作者:赵刘伟 时间:2020-05-14 浏览量:
给定两个包含数组元素的数组,任务是检查两个数组是否包含任何公共元素,然后返回True,否则返回False。


Input: array1 = ['a', 'b', 'c', 'd', 'e']       array2 = ['f', 'g', 'c']Output: true
Input: array1 = ['x', 'y', 'w', 'z']       array2 = ['m', 'n', 'k']Output: false
对于这个问题,有许多方法可以解决JavaScript中的此问题,下面讨论其中一些方法。
方法1:暴力破解方法

  • 比较第一个数组中的每个项目和第二个数组中的每个项目。
  • 遍历array1并从头到尾进行迭代。
  • 遍历array2并从头到尾进行迭代。
  • 比较从array1到array2的每个项目,如果找到任何公共项目,则返回true,否则返回false。


<script>
// Declare two array const array1 = ['a', 'b', 'c', 'd']; const array2 = ['k', 'x', 'z'];
// Function definiton with passing two arrays function findCommonElement(array1, array2) {
   // Loop for array1    for(let i = 0; i < array1.length; i++) {
       // Loop for array2        for(let j = 0; j < array2.length; j++) {
           // Compare the element of each and            // every element from both of the            // arrays            if(array1[i] === array2[j]) {
               // Return if common element found                return true;            }        }    }
   // Return if no common element exist    return false;  }
document.write(findCommonElement(array1, array2)) </script>
输出:


false
时间复杂度: O(M * N)
方法2:

  • 创建一个空对象并遍历第一个数组。
  • 检查第一个数组中的元素是否存在于对象中。如果不存在,则在数组中分配属性===元素。
  • 遍历第二个数组,并检查第二个数组中的元素是否在创建的对象上存在。
  • 如果元素存在,则返回true,否则返回false。

例:


<script>
// Declare Two array const array1 = ['a', 'd', 'm', 'x']; const array2 = ['p', 'y', 'k'];
// Function call function findCommonElements2(arr1, arr2) {
   // Create an empty object    let obj = {};
       // Loop through the first array        for (let i = 0; i < arr1.length; i++) {
           // Check if element from first array            // already exist in object or not            if(!obj[arr1[i]]) {
               // If it doesn't exist assign the                // properties equals to the                  // elements in the array                const element = arr1[i];                obj[element] = true;            }        }
       // Loop through the second array        for (let j = 0; j < arr2.length ; j++) {
       // Check elements from second array exist        // in the created object or not        if(obj[arr2[j]]) {            return true;        }    }    return false; }
document.write(findCommonElements2(array1, array2)) </script>
输出:


false
时间复杂度: O(M + N)
方法3:

  • 使用内置的ES6函数some()遍历第一个数组的每个元素并测试该数组。
  • 在第二个数组中使用内置函数include()来检查元素是否在第一个数组中。
  • 如果元素存在,则返回true,否则返回false


<script>
// Declare two array const array1= ['a', 'b', 'x', 'z']; const array2= ['k', 'x', 'c']  
// Iterate through each element in the // first array and if some of them  // include the elements in the second // array then return true. function findCommonElements3(arr1, arr2) {    return arr1.some(item => arr2.includes(item)) }
document.write(findCommonElements3(array1, array2)) </script>                  
输出:


true


返回列表

想和你做个朋友

DO U LIKE?