比较两个数组,并返回重复值 [英] compare two arrays and return duplicate values

查看:157
本文介绍了比较两个数组,并返回重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以检索存在于同一文档的两个不同的数组元素。

How may I retrieve an element that exists in two different arrays of the same document.

例如。在帖子收集,文档具有字段的interestbycreator'和'interestbyreader。每个字段包含用户ID。

For example. In Posts collection, document has the fields 'interestbycreator' and 'interestbyreader.' Each field contain user Ids.

'interestbycreator':  //an array of ids here. IdA, idB, IdC, IdD, IdE,
'interestbyreader':  //an array of ids here. IdB, idE, iDF

基本上,我希望能够找到存在于两个数组中的所有的ID,所以这应该是美洲开发银行和IDE。

Basically I wish to find all the ids that exist in both arrays, so that should be IdB and 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.

例检索所有ID interestbyreader

Example to retrieve all Ids from 'interestbyreader

var interestbypostcreater = Posts.find({_id: Meteor.user().profile.postcreated[0]}, {fields: {interestbyreader: 1}}).fetch();
var interestedReaderIds = _.chain(interestbypostcreator).pluck('interestbyreader').flatten().value();

假设我有另一阵列interestbycreator存储在一个名为interestIdcreator变量,对它们进行比较,找到重复,并返回这些重复?

Assume I have the other array 'interestbycreator' stored in a variable called interestIdcreator, can they be compared to find duplicates and return these duplicates?

推荐答案

由于Saimeunt指出的那样,这是可以做到的。

As Saimeunt pointed out, it can be done as

var x = ['IdA', 'idB', 'IdC', 'IdD', 'IdE'];
var y = ['idB', 'IdE', 'IdF'];

var z = _.intersection(x, y);

这篇关于比较两个数组,并返回重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆