shamon shamsudeen
shamon shamsudeen

Reputation: 5848

Lodash difference of two arrays that matches only one key

I have an array's like this

var old = [ { id: 1, name: 'Super edit' },
  { id: 2, name: 'new item' },
  { id: 19, name: 'new item' } ]

var new = [ { id: 1, name: 'Super edit' },{ id: 2, name: 'new item' }]

I would like to get the difference of the above two that don't matches the key id.

Expected result:

[{ id: 19, name: 'new item' }]

What I've tried is

_.differenceWith(old,new,_.isEqual) but its checks both id and name how can i get array's that matches only the key id

Upvotes: 0

Views: 350

Answers (2)

Akrion
Akrion

Reputation: 18515

You have options as usual with _.lodash.

If you want to mutate the array then use _.pullAllBy

If you do not want to mutate the array use _.differenceBy

var old = [{ id: 1, name: 'Super edit' }, { id: 2, name: 'new item' }, { id: 19, name: 'new item' } ]
var current = [{ id: 1, name: 'Super edit' }, { id: 2, name: 'new item' }]

console.log(_.differenceBy(old, current,'id'))  // this will NOT mutate
console.log(old, current)  // Notice no changes to any of the arrays

console.log(_.pullAllBy(old, current,'id'))    // this will
console.log(old, current)  // Notice old array is now changed
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

Use _.differenceBy() with the id as the iteratee shorthand.

Notes: new is a reserved word in javascript, and can't be used for variable names.

const oldArr = [{ id: 1, name: 'Super edit' },{ id: 2, name: 'new item' },{ id: 19, name: 'new item' }]

const newArr = [ { id: 1, name: 'Super edit' },{ id: 2, name: 'new item' }]

const result = _.differenceBy(oldArr, newArr, 'id')

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

Upvotes: 1

Related Questions