meteorBuzz meteorBuzz - 1 year ago 86
Javascript Question

compare two arrays and return duplicate values

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.

'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.

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

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?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download