Developer Strange
Developer Strange

Reputation: 2198

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

Upvotes: 0

Views: 163

Answers (3)

Washington Guedes
Washington Guedes

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:

  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 :)

Upvotes: 1

guest271314
guest271314

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

Nina Scholz
Nina Scholz

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

Related Questions