3种方法快速查找两个数组是否在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
原文地址:https://www.cnblogs.com/xiewangfei123/p/12887137.html