Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array objects difference javascript angularjs

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.

like image 449
Mustang Avatar asked Apr 27 '15 21:04

Mustang


1 Answers

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));
like image 67
floribon Avatar answered Nov 17 '22 13:11

floribon