我的用例的 JS 列表交集
我是一个 javascript 新手,所以请耐心等待。我的列表如下:
var list1 = ['a','b','c'];
var list2 = ['c','d','e'];
var list3 = ['f','g'];
如您所见,list1 和 list2 在“c”处相交,而 list3 与 list1 和 list2 都不相交。
结果应该是
['a','b','c','d','e'],['f','g'] // Two arrays
我们合并了 list1 和 list2,因为它们相交,同时保留 list3 不变。另一个例子:
var list1 = ['a','b','c'];
var list2 = ['d','e','f'];
var list3 = ['f','g','a'];
这里我们看到list1和list2不相交,list1与list3在“a”处相交,list2与list3在“f”处相交。因此,由于所有 3 个相交,返回的结果将是:
['a','b','c','d','e','f','g'] // One array
任何帮助表示赞赏
KA
PS:我确实在网站上搜索了类似的问题,并且遇到了一个 n 的交集通过 JS 列出 它类似,但不适合我的用例。
I am a javascript newbie so bear with me. I have lists as so:
var list1 = ['a','b','c'];
var list2 = ['c','d','e'];
var list3 = ['f','g'];
As you see, list1 and list2 intersect at 'c' while list3 is disjoint from both list1 and list2.
The result should be
['a','b','c','d','e'],['f','g'] // Two arrays
We have combined list1 and list2 since they intersect while leaving list3 as is. Another example:
var list1 = ['a','b','c'];
var list2 = ['d','e','f'];
var list3 = ['f','g','a'];
Here we see list1 and list2 don't intersect, list1 intersects with list3 at 'a' and list2 intersects list3 at 'f'. So since all 3 intersect, the result returned would be:
['a','b','c','d','e','f','g'] // One array
Any help is appreciated
KA
PS: I did search the site for a similar problem and I came across one intersection of n lists via JS Its similar but doesn't serve my use case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你有两个列表的交集和并集函数,你可以用这个逻辑得到你想要的:
当你循环遍历 merged 的所有元素时,你只需要小心地从 merged 中删除 b 。从最后一个元素到第一个元素迭代合并可能会更简单。
下划线库是查找交集和并集函数的好地方。
If you have two-list intersection and union functions, you can get what you want with this logic:
You just have to be a little careful about removing b from merged while you are looping through all the elements of merged. It might be simpler to iterate through merged from the last to the first element.
The underscore library is a nice place to find functions for intersection and union.
尝试
try