-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.

4
  • Searching for your exact title bring up a lot of helpful information:google.com/… Commented Mar 12, 2014 at 12:54
  • @JordanD, JavaScript, not Java. Commented Mar 12, 2014 at 12:58
  • @Andy this is javascript, not a java issue Commented Mar 12, 2014 at 12:58
  • @PaulRad, I know. What was the problem with the link I added? Commented Mar 12, 2014 at 12:59

3 Answers 3

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

There's an error in your code. if (i.name == aName) { should be if (entry.name == aName) {.
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/

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.