I have 2 array objects and I want to get the difference between them as follows:

array1 = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"APP","id":"tool:app"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}, {"name":"USU","id":"tool:usu"}]

array2 = [{"name":"APP","id":"tool:app"}, {"name":"USU","id":"tool:usu"}]

result = [{"name":"MPCC","id":"tool:mpcc"}, {"name":"AII","id":"tool:aii"}, {"name":"VZZ","id":"tool:vzz"}]

Here is the code:

$scope.initial = function(base, userData){
    var result = [];
    angular.forEach( base, function(baseItem) {
        angular.forEach( userData, function( userItem ) {
            if ( baseItem.id !== userItem.id ) {
                if (result.indexOf(baseItem) < 0) { 
                    result.push(baseItem);
                }
            }
        });
    });
    return result;
}
$scope.initial(array1, array2);

The problem with the above code is I dont get the desired result. Please let me know what is going wrong.

share|improve this question
up vote 6 down vote accepted

That is not related to Angular.

You could do something like this:

var result = array1.filter(function(item1) {
  for (var i in array2) {
    if (item1.id === array2[i].id) { return false; }
  };
  return true;
});

Or with ES6 syntax:

var result = array1.filter(i1 => !array2.some(i2 => i1.id === i2.id));
share|improve this answer
    
I am really sorry if my angularjs tag was misleading.This solution worked like a charm. Thank you so much. – SAM Apr 27 '15 at 22:00
    
pretty good method... thanks @floribon – Mohideen ibn Mohammed Dec 29 '15 at 9:30
    
Working perfectly fine – Dijo Oct 18 '16 at 21:54

I think this is not related to Angular itself. You're looking for an algorithm to compute a difference between 2 sets.

The topic has already been discussed. You may also be interested on this underscore plugin

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.