5

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.

Mustang
  • 604
  • 2
  • 13
  • 32

2 Answers2

12

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));
floribon
  • 19,175
  • 5
  • 54
  • 66
0

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

Community
  • 1
  • 1
Vincenzo
  • 1,549
  • 1
  • 9
  • 17