计算 JavaScript 中两个数组的公共元素(归约函数)

Counting common elements of two Arrays in JavaScript (reduce function)

我在计算两个数组中公共元素的个数时遇到了意想不到的结果。当我使用 reduce 函数时,它不起作用。但是 filter 版本 returns 正确的结果。我想知道我的 reduce 版本有什么问题。

var ls = [1, 2, 3, 4, 5];
var ms = [4, 5, 6, 1, 2];

console.log(ls.reduce((acc, e) => (ms.includes(e) ? 1 + acc : 0), 0));
// 2, incorrect

console.log(ls.filter(e => ms.includes(e)).length);
// 4, correct

因为在您的 reduce 版本中,当找不到元素时,您会将 acc 重置为零,而不是按原样返回

var ls = [1, 2, 3, 4, 5];
var ms = [4, 5, 6, 1, 2];

console.log(ls.reduce((acc, e) => (ms.includes(e) ? 1 + acc : acc), 0));
// -----------------------------------------------------------^ here
// 4, now corrected

   

当作为 reduce 函数的第一个参数的回调函数命中 ls 数组中的第三项“3”时,它发现它不是 ms 数组的成员。这会导致三元运算符 return 右侧表达式 0,这会重置累加器变量 acc。这将从 0 重新开始计数。

相反,您应该 return 累加器变量的当前值而不是 0,如下所示:

console.log(ls.reduce(acc,e) => (ms.includes(e) ? 1 + acc: acc), 0));

这将为您提供 4 个匹配元素的正确计数。