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?
As saimeunt said in the comments when you have access to underscore use intersection but you can also do it with plain 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.
Credits to https://stackoverflow.com/a/14930567/441907
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With