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.

5
  • 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() which discards the sub-loop. Commented May 30, 2012 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. <stackoverflow.com/questions/27030/…> might help Commented May 30, 2012 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 Commented May 30, 2012 at 14:49
  • This was exactly I was looking stackoverflow.com/questions/9736804/… Commented May 31, 2012 at 5:15
  • The answer I was looking was in this post stackoverflow.com/questions/9736804/… Commented Aug 7, 2012 at 15:24

2 Answers 2

0

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

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

Comments

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.

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.