LetMeCodeYou
LetMeCodeYou

Reputation: 320

How to get difference of two JS objects

New to JavaScript and have very limited knowledge of JS objects. I want to get difference of two JS objects.

a=[{"month":1,"year":2015},{"month":2,"year":2015},{"month":3,"year":2015},{"month":4,"year":2015},{"month":5,"year":2015}];
b=[{"month":1,"year":2015},{"month":2,"year":2015},{"month":5,"year":2015}];

The result I dreamed should be

result=[{"month":3,"year":2015},{"month":4,"year":2015}];

I got the above format using JSON.stringify.

Upvotes: 3

Views: 131

Answers (1)

dReAmEr
dReAmEr

Reputation: 7194

Below should work for you,just use filter on array.

var a=[{"month":1,"year":2015},{"month":2,"year":2015},{"month":3,"year":2015},{"month":4,"year":2015},{"month":5,"year":2015}];
var b=[{"month":1,"year":2015},{"month":2,"year":2015},{"month":5,"year":2015}];

var diff = a.filter(function(a){
    return b.filter(function(b){
        return b.month == a.month && b.year == a.year
    }).length == 0
});

console.log(diff);

Upvotes: 4

Related Questions