-3

I had taken two array of objects in javascript

arr1 = [{"name":"prudhvi", "age":"12"},
        {"name":"pavan", "age":"13"},
        {"name":"prudhvi", "age":"15"}];

arr2 = [{"name":"Sai", "age":"12"},
        {"name":"Shiva", "age":"13"},
        {"name":"prudhvi", "age":"12"}];
  1. Actually I want to compare both arrays based on name only. Here, name prudhvi is repeated I want to delete that object from arr2.

  2. Another thing is I want unique items in arr1. If there is any duplicate object, I want to delete it from this array.

Rémi Breton
  • 4,209
  • 2
  • 22
  • 34
bakkupavan
  • 9
  • 1
  • 5

3 Answers3

0

You could create a helper function for this, as the array contains new Object declarations (meaning they hold the same value, but won't reference the same Object as they're two separate entities). You should iterate over the array and see if it contains the expected value, and if so remove it. Something like this:

function removeDuplicateName( aArray, aName )
{
    var i = aArray.length; // get Array length

    while ( i-- )
    {
        var entry = aArray[ i ];   // get object at position i in array
        if ( entry.name == aName ) {   // object matches name
            aArray.splice( i, 1 ); // remove object at array position
            break;                 // if name is expected to unique, break operation
        }
    }
}
Igor Zinken
  • 884
  • 5
  • 19
0

you can use a help function like...

function compareObjs( obj1, obj2, keys ){


    for(var i = 0; i < keys.length; i++){

        if( obj1[keys[i]] !== obj2[keys[i]] )  return false;

    }

    return !!keys.length;

}

this function 'll iterate in keys and return if all are equals... SEE IN JSFIDDLE -> http://jsfiddle.net/dzkzL/1/

Luan Castro
  • 1,184
  • 7
  • 14
0
var diff = $(array1).not(array2).get();

if diff is null you have the same array otherwise it will contain the difference b/w two arrays

001
  • 13,291
  • 5
  • 35
  • 66
Akash Yadav
  • 861
  • 7
  • 11