Saumay Paul
Saumay Paul

Reputation: 425

Compare two arrays of objects excluding a property using lodash

I am able to get the difference between two arrays of objects using _.differenceWith like this:

_.differenceWith(arr1, arr2, _.isEqual)

Suppose I have arr1 and arr2 as:

    let arr1= [
      {
        id:1,
        val1:{
          pre:1,
          foo:2
        }
      }
      ]

    let arr2= [
      {
        id:3,
        val1:{
          pre:1,
          foo:2
        }
      },
      ]

The ids are different, but the val1 properties are same.

So, I want to compare the arrays excluding id.

How can I achieve this using lodash or simple JS?

Upvotes: 1

Views: 3218

Answers (2)

Keith
Keith

Reputation: 24191

You can use _.omit to omit id in when doing isEqual..

eg.

let arr1= [
  {id:1, val1:{ pre:1, foo:2 }},
  {id: 4, val1: { pre: 3, addThis: 'just to check' }}
];

let arr2= [{ id:3, val1:{ pre:1, foo:2 }}];

console.log(_.differenceWith(arr1, arr2, (a, b) => {
  return _.isEqual(
    _.omit(a, ['id']),
    _.omit(b, ['id'])
  )
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

Use the _.differenceWith() comparator function to compare the val1 property of the objects:

const arr1 = [{"id":1,"val1":{"pre":1,"foo":2}}]
const arr2 = [{"id":3,"val1":{"pre":1,"foo":2}}]

const result = _.differenceWith(arr1, arr2, (a, b) => _.isEqual(a.val1, b.val1))

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

Upvotes: 1

Related Questions