I have two arrays of objects and I only want to retrieve the first matching object from one array if it is found in the other array. I need to stop the search after finding the first match, but I am having trouble breaking out of the loop.
Example 1:-
var array1 = [{name:'Ram',lastname:'kumar'},{name:'Shyam',lastname:'kumar'},{name:'Mohan',lastname:'kumar'},{name:'Amit',lastname:'kumar'}];
var array2 = [{name:'Anil',lastname:'kumar'},{name:'Shyam',lastname:'kumar'},{name:'Mohan',lastname:'kumar'},{name:'Anjali',lastname:'kumari'}];
Check if any objects from array2 exist in array1, then return the first matching object from array2.
Output: [{name:'Shyam',lastname:'kumar'}]
Example 2 :-
var array1 = [{name:'Ram',lastname:'kumar'},{name:'Shyam',lastname:'kumar'},{name:'Mohan',lastname:'kumar'},{name:'Amit',lastname:'kumar'}];
var array2 = [{name:'Anil',lastname:'kumar'},{name:'Arti',lastname:'kumari'},{name:'Mohan',lastname:'kumar'},{name:'Anjali',lastname:'kumari'}];
Output : [{name:'Mohan',lastname:'kumar'}]
//code
var a = [{name:'Ram',lastname:'kumar'},{name:'Shyam',lastname:'kumar'},{name:'Mohan',lastname:'kumar'},{name:'Amit',lastname:'kumar'}];
var b = [{name:'Anil',lastname:'kumar'},{name:'Shyam',lastname:'kumar'},{name:'Mohan',lastname:'kumar'},{name:'Anjali',lastname:'kumari'}];
var c = [];
b.forEach(function(user) {
var exists = false;
for (let i=0; i<a.length && !exists; i++){
exists = a[i].name === user.name ;
}
if(exists===true)
{
c.push(Object.assign({},user,{exists}));
return;
}
});
console.log(c);