Search code examples
javascriptlodash

Comparing a particular key in 2 array of objects


Is there a way with lodash, where in result I do not have an object that satisfies a particular condition. For example,

o1 = [
  {name: "a", id: 2, key: 33},
  ..,
]

o2 = [
 {name: "ab", id: 2, key: 133}
]

Is there a way with lodash where the resultant array only includes the object that does not have the ids already present in o2. For example, resultant object after comparing o1 and o2 must not have the object from o2 because id=2 already exists in o1.


Solution

  • You can use _.differenceBy() and use the id of the point of reference:

    const o1 = [{id: 1, name: 'a'},{id: 2, name: 'b'},{id: 3, name: 'c'}]
    const o2 = [{id: 1, name: 'b'}]
    
    const result = _.differenceBy(o1, o2, 'id')
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>