【问题标题】:Lodash - Select elements that are not in the array [duplicate]Lodash - 选择不在数组中的元素[重复]
【发布时间】:2019-01-16 13:12:21
【问题描述】:

我有以下数组:

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

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

所以下一个数组是:

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

如何与前一个比较,得到一个包含排除项的数组?

[
  {
    id: 3
  }
]

正确的问题

Lodash - DifferenceBy with different identity

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    如果您想根据id 找到差异,可以使用 Lodash differenceBy 方法并传递 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>

    【讨论】:

    • 如果const next = [{"id":1},{"id":2},{"id":4}]const next = [{"contact_id":1},{"contact_id":2},{"contact_id":4}]
    • @Caio Kawasaki 查看更新。
    猜你喜欢
    • 1970-01-01
    • 2015-04-12
    • 2012-01-23
    • 1970-01-01
    • 2013-12-30
    • 2015-09-21
    • 2018-08-10
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多