javascript 比较两个数组并返回重复值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26343295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
compare two arrays and return duplicate values
提问by meteorBuzz
How may I retrieve an element that exists in two different arrays of the same document.
如何检索存在于同一文档的两个不同数组中的元素。
For example. In Posts collection, document has the fields 'interestbycreator' and 'interestbyreader.' Each field contain user Ids.
例如。在 Posts 集合中,文档具有字段“interestbycreator”和“interestbyreader”。每个字段都包含用户 ID。
'interestbycreator': //an array of ids here. IdA, idB, IdC, IdD, IdE,
'interestbyreader': //an array of ids here. IdB, idE, iDF
Basically I wish to find all the ids that exist in both arrays, so that should be IdB and IdE.
基本上我希望找到两个数组中存在的所有 id,所以应该是 IdB 和 IdE。
I am able to pluck all the values from an array with underscore and store them in a variable. Can they be compared to each other this way and return duplicates? Or can someone shed some light on another solution.
我能够从带有下划线的数组中提取所有值并将它们存储在一个变量中。它们可以通过这种方式相互比较并返回重复项吗?或者有人可以对另一种解决方案有所了解。
Example to retrieve all Ids from 'interestbyreader
从“interestbyreader”中检索所有 Id 的示例
var interestbypostcreater = Posts.find({_id: Meteor.user().profile.postcreated[0]}, {fields: {interestbyreader: 1}}).fetch();
var interestedReaderIds = _.chain(interestbypostcreator).pluck('interestbyreader').flatten().value();
Assume I have the other array 'interestbycreator' stored in a variable called interestIdcreator, can they be compared to find duplicates and return these duplicates?
假设我将另一个数组 'interestbycreator' 存储在名为 interestIdcreator 的变量中,是否可以比较它们以查找重复项并返回这些重复项?
回答by Nick Russler
As saimeuntsaid in the comments when you have access to underscore use intersectionbut you can also do it with plain javascript:
正如saimeunt在评论中所说,当您可以使用下划线使用交集时,您也可以使用普通的javascript 来做到这一点:
var x = ['IdA', 'idB', 'IdC', 'IdD', 'IdE'];
var y = ['idB', 'IdE', 'IdF'];
var z = x.filter(function(val) {
return y.indexOf(val) != -1;
});
console.log(z);
The array z
contains the double entries then.
然后该数组z
包含双项。
Credits to https://stackoverflow.com/a/14930567/441907
回答by meteorBuzz
As Saimeunt pointed out, it can be done as
正如 Saimeunt 指出的那样,可以这样做
var x = ['IdA', 'idB', 'IdC', 'IdD', 'IdE'];
var y = ['idB', 'IdE', 'IdF'];
var z = _.intersection(x, y);