Gowtham V Gowtham V - 4 months ago 9
jQuery Question

get element from array which is not in first array of object

enter image description hereI 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'}]

Answer

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.