Thian Kian Phin Thian Kian Phin - 1 month ago 8
jQuery Question

Check if array of object value exist in another array but different length

I have 2 array of object, just want to check b exist in a, if yes add a new property. but the length of b is dynamic. I will got error of undefined of b.

var a = [{name:'john'},{name:'james'},{name:'jordan'},{name:'joe'}];
var b = [{name:'john'},{name:'joe'}];

var exist = 0;
var c = _.map(a,function(result,i){
exist = b[i].name.indexOf(a.name) > -1 ? exist = 1 : exist = 0;

return _.extend({},c,{'exist':exist});
});


any clue?

Answer

I would iterate over b objects and for each of them check if they exists in A, like in the following example.

    var a = [ { _id: '5815adb4badf3f311a2cd25b', username: 'david&jane' },
    { _id: '5815e40e136c8e33b65b3478', username: 'david+jane' } ];
    var b = [ { username: 'david&jane' },
              { username: 'david<3jane' },
              { username: 'david+jane' },
              { username: 'davidjane' } 
    ]
    var c = [];

    b.forEach(function(user) {
      var exists = false;
      for (let i=0; i<a.length && !exists; i++){
          exists = a[i].username === user.username ;
      }
      
      c.push(Object.assign({},user,{exists}));
    });

    console.log(c);