Lodash-选择不在数组中的元素

时间:2019-01-16 13:12:21

标签: javascript lodash

我有以下数组:

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

我的应用程序每隔5秒就会收到一个新数组,我需要比较下一个数组之间的差异...

所以下一个数组是:

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

如何与上一个比较并获得包含排除项的数组?

[
  {
    id: 3
  }
]

正确的问题

Lodash - DifferenceBy with different identity

1 个答案:

答案 0 :(得分:2)

如果您想基于differenceBy找到区别,可以使用Lodash id方法并传递id属性。否则,您可以使用_.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>

如果要检查其他键或ID属性名称,可以使用differenceWith并通过自定义的相等性检查功能。

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>