【问题标题】:Lodash uniqWith, how say lodash keep last duplicateLodash uniqWith,如何说 lodash 保持最后一个重复
【发布时间】:2019-05-29 13:37:40
【问题描述】:

您好,我正在使用 lodash uniqWith 方法删除数组中具有相同 ID 的重复项。

但 lodash 保留第一个重复项。 但我不想保留最后一个重复的项目。

我能做些什么呢?

var result = _.uniqWith(editedData, function(arrVal, othVal) {
      return arrVal.id === othVal.id;
    });
    console.log(result)

【问题讨论】:

    标签: javascript arrays object ecmascript-6 lodash


    【解决方案1】:

    最简单的方法?首先反转数组(在克隆它以避免突变之后)。

    var result = _.uniqWith(_.reverse(_.clone(editedData)), function(arrVal, othVal) {...});
    

    您还可以简化代码:

    var result = _.uniqWith(_.reverse(_.clone(editedData)), ({ id: a }, { id: b }) => a === b);
    

    【讨论】:

    • 反向会改变原始数组
    • _.reverse(_.clone(editedData)) 会不会更好@OriDrori?
    • 它会变异克隆,而不是原始,所以是的。您还可以使用 spread 来获得浅层克隆。
    • 你拯救了我的一天,谢谢 :) 很好的方法,反向它有效
    • 没问题@user3348410,总是乐于提供帮助。
    【解决方案2】:

    您可以使用_.flow() 创建一个 uniqByLast 函数。使用_.keyBy()通过id获取对象,使用_.values()获取数组:

    const { flow, partialRight: pr, keyBy, values } = _
    
    const lastUniqBy = iteratee => flow(
      pr(keyBy, iteratee),
      values
    )
    
    const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]
    
    const result = lastUniqBy('id')(arr)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

    同样的想法使用 lodash/fp:

    const { flow, keyBy, values } = _
    
    const lastUniqBy = iteratee => flow(
      keyBy(iteratee),
      values
    )
    
    const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]
    
    const result = lastUniqBy('id')(arr)
    
    console.log(result)
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 2019-03-31
      • 2015-05-05
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      相关资源
      最近更新 更多