Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
meteorBuzz Avatar asked Oct 13 '14 15:10

meteorBuzz


2 Answers

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

like image 178
Nick Russler Avatar answered Nov 07 '22 06:11

Nick Russler


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);
like image 31
meteorBuzz Avatar answered Nov 07 '22 05:11

meteorBuzz