Search code examples
javascriptlodash

Lodash - Select elements that are not in the array


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:

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

How can I compare with the previous and get an array with the excluded item?

[
  {
    id: 3
  }
]

Right question

Lodash - DifferenceBy with different identity


Solution

  • You could use Lodash differenceBy method and pass id prop if you want to find difference based on id. Otherwise you can use _.differenceWith(prev, next, _.isEqual)

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

    In case you want to check for different keys or id prop names you can use differenceWith and pass custom equality check function.

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