【问题标题】:How can I use reduce to calculate the intersection of multiple arrays?如何使用 reduce 计算多个数组的交集?
【发布时间】:2018-05-12 19:06:22
【问题描述】:

例子:

myArray = [[1,2,3,4],
           [2,3,4,5], 
           [3,4,5,6]
          ];

预期输出:

newArray = [3,4]

如何生成一个包含所有 3 个数组中的值的新数组?

【问题讨论】:

  • 您想使用reduce 是因为您认为这是正确的做法,还是因为您只是想学习如何使用它?
  • 我确实想了解这个方法。不知道有没有更有效的方法来解决这个问题。
  • 如果你只想了解reduce,那么这个问题真正具有挑战性的版本是使用reduce没有其他数组方法。

标签: javascript arrays reduce


【解决方案1】:

在归约时,返回累加器与被迭代的当前子数组的交集:

const myArray = [[1,2,3,4], [2,3,4,5], [3,4,5,6]];
const intersection = myArray.reduce((a, arr) => (
  a.filter(num => arr.includes(num))
));
console.log(intersection);

【讨论】:

  • a.filter(num => arr.includes(num) 会不会更好?如果其中一个数组有 100 万个项目,您的代码将无法正常运行。
  • 你说得对,过滤较小的数组会更高效,但在这里几乎可以肯定不重要。
【解决方案2】:

您可以使用.filter()提取匹配值:

let myArray = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]];

let intersect = ([f, ...r]) => f.filter(v => r.every(a => a.includes(v)));

console.log(intersect(myArray));

【讨论】:

  • 就我个人而言,我发现通过具有默认值的参数“偷偷地”引入新变量fr 的风格令人反感。然后,在将a 用作第二个参数的默认值之后,您甚至不再在任何地方使用它。为什么不直接写成let intersect = ([f, ...r]) => ...?除此之外,这是一个很好的解决方案,只要您认为 OP 使用 reduce 的愿望只是一个建议。
  • 非常感谢@torazaburo。你是绝对正确的。我已经更新了我的答案并学到了一些新东西:)
  • @torazaburo 我有问题要问你吗?您之前的 SO 帐户发生了什么?如果我没记错的话,你之前在这里的个人资料非常好?
猜你喜欢
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 2019-10-28
  • 2012-02-11
  • 2020-12-04
  • 2016-08-01
  • 1970-01-01
相关资源
最近更新 更多