javascript - 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 |
解决方案
我们可以在一个函数上构建它,该函数采用列表集合的交集。
这里我们有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 上提问时,请展示您自己的尝试。
推荐阅读
- rust - 对拥有列表的元素进行引用的结构使用生命周期的正确方法是什么?
- php - 如何修复 Jodit 上传器中 JSON 数据错误的第 1 行第 1 列的意外字符
- c++ - 为什么动态转换的指针执行为 NULL 的派生类对象?
- python - 如何将两个列表添加到一个新列表中而不在 Python 中合并它们?
- c++ - 用大括号初始化类类型的对象时(直接列表初始化),参数在哪里传递?
- php - 如果在 Laravel Query 中计数超过 3,如何选择项目
- javascript - 拖动时更改svg的背景
- javascript - Angular Animations - 如何在状态之间保持样式?
- java - 如何在 ActivityResultLauncher 中返回结果
- javascript - 通过在javascript中使用ckeditor获取存储在db中的带有html标签的数据