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.

2 Answers 2

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

2 Comments

I am really sorry if my angularjs tag was misleading.This solution worked like a charm. Thank you so much.
Working perfectly fine
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

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.