Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Get the JSON objects that are not present in another array

I have two arrays.

array1 = [
 {'id':1},
 {'id': 2}
]

and

array2 = [
 {'idVal':1},
 {'idVal': 2},
 {'idVal': 3},
 {'idVal': 4}
]

I need a optimal way, lodash if possible so that i can compare these two arrays and get a result array that has object present in array2 and not in array1. The keys have different name in both arrays. So the result will be,

res = [
  {'idVal': 3},
  {'idVal': 4}
]

Upvotes: 1

Views: 1338

Answers (5)

Chandrakant Thakkar
Chandrakant Thakkar

Reputation: 978

array1 = [
 {'id':1},
 {'id': 2}
]

array2 = [
 {'idVal':1},
 {'idVal': 2},
 {'idVal': 3},
 {'idVal': 4}
]

var array1Keys=array1.map(function(d1){ return d1.id});

var result =array2.filter(function(d){ return array1Keys.indexOf(d.idVal)==-1 })
console.log(result);

Upvotes: 0

Freeman Lambda
Freeman Lambda

Reputation: 3655

Here's an optimized solution, not using lodash though. I created a search index containing just the values of array1, so that you can look up elements in O(1), rather than going through the entire array1 for every element in array2.

Let m be the size of array1 and n be the size of array2. This solution will run in O(m+n), as opposed to O(m*n) that you would have without prior indexing.

const array1 = [
 {'id':1},
 {'id': 2}
];

const array2 = [
 {'idVal':1},
 {'idVal': 2},
 {'idVal': 3},
 {'idVal': 4}
];

const array1ValuesIndex = {};
array1.forEach(entry => array1ValuesIndex[entry.id] = true);

const result = array2.filter(entry => !array1ValuesIndex[entry.idVal]);
console.log(result);

Upvotes: 0

David
David

Reputation: 4895

Using ES6

const result = array2.filter(item => !array1.find(i => i.idVal === item.id))

Upvotes: 3

Glitcher
Glitcher

Reputation: 1184

var array1 = [
 {'id':1},
 {'id': 2},
 {'id': 3},
 {'id': 4}
]

var array2 = [
 {'id':1},
 {'id': 3},
 {'id': 4}
]

notInArray2 = array1.reduce( function(acc, v) {
  if(!array2.find(function (vInner) {
    return v.id === vInner.id;
  })){
    acc.push(v);
  }
  return acc
}, []);

console.log(JSON.stringify(notInArray2))

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192287

Use _.differenceWith() with a comparator method. According to the docs about _.difference() (differenceWith is based on difference):

Creates an array of array values not included in the other given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array.

So array2 should be the 1st param passed to the method.

var array1 = [
  {'id': 1},
  {'id': 2}
];

var array2 = [
  {'idVal': 1},
  {'idVal': 2},
  {'idVal': 3},
  {'idVal': 4}
];

var result = _.differenceWith(array2, array1, function(arrVal, othVal) {
  return arrVal.idVal === othVal.id;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 6

Related Questions