假设我有两个数组。第一个是[12, 32, 65, 32]
,第二个是[0, 4, 12, 12]
我将如何创建一个函数来查看每个数组的每个数字,并查看多少个数组彼此相等。这是我正在尝试做的要点:
let array1 = [12, 32, 65, 32];
let array2 = [0, 4, 12, 12];
var counter = 0;
for (var i=0; i<= array1.length; i++) {
//this is where I lose it
for (var j=0; i<= array2.length; j++) {
if (array1[i] == array2[j]) {
counter++;
console.log(counter);
}
}
}
很显然,上面的函数希望允许您将1
作为日志,因为第一个数组只有一个12
。我无法弄清楚如何仅给出1
的输出,其中array1的输出为12,array2中的输出为2。当然,如果array1中有两个12,则输出应为2。
答案 0 :(得分:1)
您可以使用Set
来使数组仅包含唯一的数字,并有效地测试一个数字是否在另一个数组中。然后,您可以迭代一个集合,如果数字在另一个集合中,则增加计数:
let array1 = [12, 32, 65, 32];
let array2 = [0, 4, 12, 12];
function countSame(a1, a2){
/* Make sets */
let [s1, s2] = [new Set(a1), new Set(a2)]
let count = 0
/* iterate and count */
for (n of s1){
if (s2.has(n)) count++
}
return count
}
console.log(countSame(array1, array2))
// with more dupes - return 2 because 1 and 3 are common
console.log(countSame([1, 1, 2, 3, 4], [1, 3, 3, 6, 7]))