gpt4 book ai didi

javascript - 如何使用下划线获取基于对象属性的唯一数组

转载 作者:IT王子 更新时间:2023-10-29 03:09:14 28 4
gpt4 key购买 nike

我有一个对象数组,我想从中获取一个仅基于单个属性的唯一新数组,是否有一种简单的方法可以实现此目的?

例如。

[ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]

将导致 2 个 name = bill 的对象被删除一次。

最佳答案

使用 uniq功能

var destArray = _.uniq(sourceArray, function(x){
return x.name;
});

或单行版

var destArray = _.uniq(sourceArray, x => x.name);

来自文档:

Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.

在上面的例子中,函数使用对象名称来确定唯一性。

关于javascript - 如何使用下划线获取基于对象属性的唯一数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20739575/

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