返回阵列的函数,该数组是其他两个数组的交点
function arraysCommon(array1, array2) {
return array1.filter(x => array2.includes(x));
}
此功能无法按照我想要的方式工作。 例如给定array1 = [1,2,3,2,1]
和array2 = [5,4,3,2,1]
它返回[1,2,3,2,1]
,因为在两个数组中都可以看到elements 1,2,3
。 但是我希望它以该顺序返回[1,2,3]
,因为1,2,3
在array2
和被视为单独的实体。
因此,功能几乎应该是
- 第一个数组中的每个元素都可以映射到第二个数组中的最多元素。
- 每个数组中的重复元素被视为单独的实体。
- 第一个数组决定了我试图循环循环阵列的顺序
,并检查和比较每个数组中的重复项数量,但我似乎无法使逻辑正常工作。有其他方法可以解决这个问题吗?
我附上了两个Venn图的图像,可以阐明差异
function arraysCommon(array1, array2) {
return array1.filter(x => array2.includes(x));
}
This function does not work the way I want it to.
For instance given array1 = [1,2,3,2,1]
and array2 = [5,4,3,2,1]
it returns [1,2,3,2,1]
, since the elements 1,2,3
are seen in both arrays.
But I want it to return [1,2,3]
in that order since 1,2,3
are seen only once in array2
and are treated as seperate entities.
So pretty much the functionality should be that
- Each element in the first array can map to at most one element in the second array.
- Duplicated elements in each array are treated as separate entities.
- the first array determines the order
I have attempted to loop through the arrays and check and compare the number of duplicates in each array but I can't seem to get the logic working correctly. Is there a different way to approach this?
I've attached an image of two Venn diagrams that might clarify the difference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不幸的是,它变得更加复杂,因为您需要知道已经添加了哪些数字。在这种情况下,您需要一个临时数组来保留结果。我们还需要跟踪数组中是否存在两次数字。
尝试以下操作:
Unfortunately, it gets more complicated because you need to know what numbers you have already added. In this case you need a temporary array to hold the result. We also need to track if a number exists in the array two times.
Try this:
通过分类和计数应该是可能的。由于当您找到类似字符时,您正在增加,所以这应该没关系:
With sorting and counting this should be possible. Since you are incrementing when you find similar characters, this should be okay:
这应该按照您的意愿起作用!
我希望这会有所帮助。干杯。
this should work as you wanted!
I hope this helps. Cheers.
您可以实现一个新的集合,Wich仅带来唯一的值,而不是从该集合中重新保留一个数组。
这样的事情:
You can instance a new Set, wich brings only unique values and than retorn a array from this set.
Something like this: