Search code examples
javascriptlodash

Lodash - DifferenceBy with different identity


I have the following array:

[
  {
    id: 1
  },
  {
    id: 2
  },
  {
    id: 3
  },
  {
    id: 4
  }
]

Every 5 seconds my application receives a new array and I need to compare the difference between the next one...

So the next array is:

[
  {
    conversation_id: 1
  },
  {
    conversation_id: 2
  },
  {
    conversation_id: 4
  }
]

Considering that identity is different. How can I compare with the previous and get an array with the excluded item?

[
  {
    id: 3
  }
]

Solution

  • Use _.differenceWith():

    const prev = [{"id":1},{"id":2},{"id":3},{"id":4}]
    const next = [{"conversation_id":1},{"conversation_id":2},{"conversation_id":4}]
    
    const diff = _.differenceWith(prev, next, ({ id }, { conversation_id }) => _.eq(id, conversation_id))
    console.log(diff)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>