SAM SAM - 2 months ago 22
AngularJS Question

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.

Answer

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));