0

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'}]

Gmv
  • 2,008
  • 6
  • 29
  • 46

3 Answers3

1

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:

  1. All non-zero numbers are true. SO link.
  2. The bitwise not (~) turns -1 into 0. MDN link.
  3. Inline arrow functions (=>) does not need return keyword. MDN link.

Hope it helps :)

Community
  • 1
  • 1
Washington Guedes
  • 4,254
  • 3
  • 30
  • 56
  • If u dont mind can u explain `obj => !~stringArr1.indexOf(JSON.stringify(obj))` this line and tell me the use of "~". – Gmv Jul 18 '16 at 05:16
0

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>
guest271314
  • 1
  • 15
  • 104
  • 177
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392