0

I have two array of objects in javascripts. Like arr1[] = {emp1,emp2,emp3} where inturn emp1 has emp1.name and emp1.address as property.

Something like

arr1={object {name='a',address='b'} {name='c',address='d'} {name='e',address='f'} }. 
arr2={object {name='a',address='b'}}. 

I wanted to compare name property of two array objects and populate the missing items into another array. So result will be result[]={'c','e'}

Whats is the efficient way in achieving this? I don't expect code, please guide me in the right direction. Thanks.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
Lolly
  • 34,250
  • 42
  • 115
  • 150
  • What I can think of is running each `arr1` value/element against all of `arr2` then calling `arr2.push(arr1[i])`, but jQuery should have an easier way to check if a value/element is `in` an array, say, [jQuery.inArray()](http://api.jquery.com/jQuery.inArray/) which discards the sub-loop. – Fabrício Matté May 30 '12 at 14:36
  • what have you tried? i would consider making a function that accepts both arrays and then returns the third array. Im not sure what you are refering to as 'missing items' so you will have to do that yourself. in the function you can use a for loop and some if statements to compare. might help – GreenGiant May 30 '12 at 14:38
  • 1
    I think this would be far more efficient if instead of an array you were using an object with nested objects where the keys of said objects were the employee unique id's. At that point you could just extend object1 with object2 resulting in object1 containing all of the employees in object2 that weren't already in object1 – Kevin B May 30 '12 at 14:49
  • This was exactly I was looking http://stackoverflow.com/questions/9736804/find-missing-element-by-comparing-2-arrays-in-javascript – Lolly May 31 '12 at 05:15
  • The answer I was looking was in this post http://stackoverflow.com/questions/9736804/find-missing-element-by-comparing-2-arrays-in-javascript – Lolly Aug 07 '12 at 15:24

2 Answers2

0

The Array.filter method might be helpful. Check out more on it here.

jwatts1980
  • 7,254
  • 2
  • 28
  • 44
0

the function could look like

      function foo(arr1,arr2){
    var arr3 = new Array();
    var x=0;
    for (var j =0; j<arr1.length; j++)
         for(var i=0; i<arr2.length; i++)
            if(arr1[j].name != arr2[i].name){
               arr3[x]=arr1[i];
               x++;
    }
 return(arr3); 
  }

This will loop through the 2 arrays and if the elements are not the same then they will be put in the third array. this is checking if any name in aarr1 is the same as in arr2. it doesn't check the other way.(ie if arr2 has an element that does not exist in arr1 it will not be put in arr3) but at least it should get you started.the function will accept the 2 arrays and return the third.

GreenGiant
  • 491
  • 1
  • 4
  • 13