1

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?

1
  • So, I want to compare the arrays excluding id. So what if later you add val2, or some other property?, as the accepted answer will fail there.. Commented Jun 25, 2020 at 11:08

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.