Lodash映射和返回唯一值

38

我有一个lodash变量;

var usernames = _.map(data, 'usernames');

生成以下结果;

[
    "joebloggs",
    "joebloggs",
    "simongarfunkel",
    "chrispine",
    "billgates",
    "billgates"
]

我该如何调整lodash语句,以使其仅返回唯一值的数组?例如:

var username = _.map(data, 'usernames').uniq();

2
你尝试过使用 uniqBy 吗?_.uniqBy(data, 'username') - The Reason
我希望数据能让我这样做...但在这种情况下,我不能。 - stackunderflow
3个回答

87

有很多种方法,但 uniq() 不是数组的方法,它是 lodash 的方法。

_.uniq(_.map(data, 'usernames'))

或者:

_.chain(data).map('usernames').uniq().value()

(第二个方法没有经过测试,可能是错误的,但它很接近。)

正如评论中提到的那样,根据您的数据实际情况,您可以在不先提取出usernames的情况下一次性完成所有操作。


1
谢谢,虽然我提到了一些特定于lodash的内容。我知道uniq()是lodash的函数。 - stackunderflow
@KarlBateman 对的,但你试图在数组上调用lodash方法。这不是lodash的工作方式;它不修改原型。 - Dave Newton
3
谢谢,更简洁地说是_(data).map('usernames').uniq().value(); - SSH This

19

你还可以使用uniqBy函数,它也接受为数组中的每个元素调用的迭代器。它接受以下两个参数,其中id是迭代器参数。

_.uniqBy(array, 'id')

2
你还需要一步:_.map(_.uniqBy(array, 'id'), 'id')(如果重复项数量巨大且对象较小,则此方法可能比已接受的答案更高效,因为中间数组将更短)。 - Dem Pilafian

0
非常简单的解决方案:
_.uniq(array.map(({ status }) => status))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接