JavaScript 如何找出两个数组是否含有共同的元素
在本文中,我们给出了两个包含数组元素的数组,任务是检查两个数组是否含有任何共同元素,如果有则返回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中解决这个问题有很多方法,其中一些在下面讨论。
检查数组中共同项的方法:
- 暴力方法:使用JavaScript循环
- 创建一个新的JavaScript对象
- 使用JavaScript Array.some()和.include()方法
方法1:暴力方法: 使用JavaScript循环
- 将第一个数组的每一项与第二个数组的每一项进行比较。
- 遍历数组1并从头到尾迭代它。
- 遍历数组2并从头到尾迭代它。
- 将数组1的每一项与数组2的每一项进行比较,如果找到任何共同项,则返回true,否则返回false。
示例: 在这个示例中,我们将使用上述方法来判断两个数组中是否包含任何共同项 Javascript 。
// Declare two array
let array1 = ['a', 'b', 'c', 'd'];
let array2 = ['k', 'x', 'z'];
// Function definition 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;
}
console.log(findCommonElement(array1, array2))
输出
false
方法2:创建一个新的JavaScript对象
- 创建一个空对象并循环遍历第一个数组。
- 检查第一个数组的元素是否存在于对象中。如果不存在,则将元素赋值给对象的属性。
- 循环遍历第二个数组,并检查第二个数组中的元素是否存在于创建的对象中。
- 如果元素存在,则返回true;否则返回false。
示例: 在这个示例中,我们将使用上述方法来判断两个数组中是否存在共同的元素。
// Declare Two array
let array1 = ['a', 'd', 'm', 'x'];
let 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
let 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;
}
console.log(findCommonElements2(array1, array2))
结果
false
方法3:使用JavaScript Array.some()和.include()方法
- 使用内置的ES6函数some()来迭代遍历第一个数组的每个元素并测试数组。
- 使用内置函数includes()与第二个数组一起检查第一个数组中是否存在元素。
- 如果存在元素,则返回true,否则返回false。
示例: 在这个示例中,我们将使用上面的方法来查找两个数组中是否存在任何共同项。
// Declare two array
let array1 = ['a', 'b', 'x', 'z'];
let 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))
}
console.log(findCommonElements3(array1, array2))
输出
true