Reputation: 2198
I have two array of objects in javascript
var arr1 = [{'a':'1'},{'b':'2'},{'c':'3'}];
var arr2 = [{'a':'1'},{'b':'2'},{'d':'4'}];
I want to get the element from arr2 which is not in the arr1.
my output will be [{'d':'4'}]
Upvotes: 0
Views: 163
Reputation: 4365
The easiest method that came my mind is using JSON.stringify:
var arr1 = [{'a':'1'},{'b':'2'},{'c':'3'}];
var arr2 = [{'a':'1'},{'b':'2'},{'d':'4'}];
stringArr1 = JSON.stringify(arr1);
var result = arr2.filter(
obj => !~stringArr1.indexOf(JSON.stringify(obj))
);
console.log(result);
But there should be better ways.
The equivalent of:
var result = arr2.filter(
obj => !~stringArr1.indexOf(JSON.stringify(obj))
);
is the common:
var result = arr2.filter(function (obj) {
var stringObj = JSON.stringify(obj);
if (stringArr1.indexOf(stringObj) != -1)
return true;
else
return false;
});
The tricks are simple, basically you need to know 3 things:
~
) turns -1 into 0. MDN link.=>
) does not need return
keyword. MDN link.Hope it helps :)
Upvotes: 1
Reputation: 1
You can use $.grep()
, .every()
, Object.keys()
var arr1 = [{'a':'1'},{'b':'2'},{'c':'3'}];
var arr2 = [{'a':'1'},{'b':'2'},{'d':'4'}];
var res = $.grep(arr2, function(v) {
return arr1.every(function(_v) {
var keys = [Object.keys(v)[0], Object.keys(_v)[0]];
return keys[0] !== keys[1] && v[keys[0]] !== _v[keys[1]]
})
});
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
Upvotes: 0
Reputation: 386680
You could use JSON.stringify
for each element of the arrays and use a hash table for checking
var arr1 = [{ 'a': '1' }, { 'b': '2' }, { 'c': '3' }],
arr2 = [{ 'a': '1' }, { 'b': '2' }, { 'd': '4' }],
arr3,
hash = Object.create(null);
arr1.forEach(function (o) {
hash[JSON.stringify(o)] = true;
});
arr3 = arr2.filter(function (o) {
return !hash[JSON.stringify(o)];
});
console.log(arr3);
Upvotes: 0