5

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?

1

2 Answers 2

19

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

Sign up to request clarification or add additional context in comments.

3 Comments

How can I get the 'return' results inside another variable? I want to preserve them as an array and not convert them so I can use the variable to query the database.Thank you for your help
You have to deep copy the source array e.g. with slice() jsfiddle.net/94mjfhyh
In exchange for memory this can be sped up by using a set for lookups.
11

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.