首页 > 解决方案 > Javascript数组操作以返回元素的交集

问题描述

我有一个这样的javascript数组productIds = [3, 4, 5, 8]。现在每个 ProductId 都有自己的兼容产品。

    3 has compatible Product -> 5, 7
    4 has compatible Product -> 7, 9
    5 has compatible Product -> 7, 1, 2
    8 has compatible Product -> 7, 4, 2

现在交集应该是产品 7,所以它应该返回 7。productIds 数组的长度可以是 n = 0 到 12。任何人都可以提出解决方案。

输入 productIds = [3, 4, 5, 8]

CompatibleProducts 的 Sql 表

ID 产品编号 兼容标识
1 3 5
2 3 7
3 4 7
4 4 9
5 5 7
6 5 1
7 5 2
8 8 7
9 8 4
10 8 2

标签: javascriptnode.jsalgorithmdata-structures

解决方案


我们可以在一个函数上构建它,该函数采用列表集合的交集。

这里我们有intersectAll,它本身就是建立在intersect. 然后我们简单地获取每个提供的产品的兼容值数组并调用intersectAll

const intersect = (xs, ys) => 
  xs .filter (x => ys .includes (x))

const intersectAll = ([x, ...xs]) => 
  x == undefined ? [] : xs .reduce (intersect, x)

const findJointCompatibles = (compatibles, ids) => 
  intersectAll (ids .map (id => compatibles [id] || []))

const compatibles = {3: [5, 7], 4: [7, 9], 5: [7, 1, 2], 8: [7, 4, 2]}

console .log (
  findJointCompatibles (compatibles, [3, 4, 5, 8])
)

这假设提供了要检查的产品列表。如果您想使用输入中的所有内容,那么它会更简单:

const findCompleteCompatibles = (compatibles) => 
  intersectAll (Object .values (compatibles))

findCompleteCompatibles (compatibles) //=> [7]

intersect并且intersectAll是真正可重用的函数,您可以保留在实用程序库中。


下次注意。在 StackOverflow 上提问时,请展示您自己的尝试。


推荐阅读