0

How to return the difference of two objects?

$scope.a = [
   {name: "Lunchmeat"},
   {name: "Apple"},
   {name: "Bread"},
   {name: "Milk"},
   {name: "Mustard"},
   {name: "Cheese"}
];
$scope.b = [
   {name: "Bread"},
   {name: "Milk"},
   {name: "Mustard"},
   {name: "Cheese"}
]; 

$.grep($scope.a, function (el) {
        if ($.inArray($scope.b,el) == -1) console.log(el);//not working
  });

The output I'm looking for is Object [{name: "Lunchmeat"},{name: "Apple"}] as this is the difference.

Can anyone help please?

2
  • convert both to sting and then do it.. it would be much easier or else loop thru one array and check if it exist in another.. simple for loop would do Commented Aug 14, 2015 at 12:10
  • Possible duplicate Difference of two $scope array in angular js Commented Aug 14, 2015 at 12:11

2 Answers 2

1

I am using underscore.js library and it's function difference:

"difference_.difference(array, *others) Similar to without, but returns the values from array that are not present in the other arrays.

_.difference([1, 2, 3, 4, 5], [5, 2, 10]); => [1, 3, 4]"

In your case it would be:

$scope.someVar =_.difference($scope.a,$scope.b);
Sign up to request clarification or add additional context in comments.

Comments

0

You're comparing objects using === (via $.inArray), which will always be false for different objects, even if they're equivalent objects.

You'll need to loop through the array looking for whether you find an object with the same name property instead of the $.inArray call. The ES5+ function Array#some is useful for this, as is the ES6+ function Array#find. (Both can be shimmed.)

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.