gpt4 book ai didi

javascript - Lodash uniqWith,怎么说lodash keep last duplicate

转载 作者:行者123 更新时间:2023-11-29 20:37:38 24 4
gpt4 key购买 nike

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

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

我能为此做什么?

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

最佳答案

您可以使用 _.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>

关于javascript - Lodash uniqWith,怎么说lodash keep last duplicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56361944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com