Lodash 地图和 return 独一无二

Lodash map and return unique

我有一个 lodash 变量;

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

产生以下结果;

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

我如何调整 lodash 语句,使其只有 returns 个唯一值数组?例如

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

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

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

或者:

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

(第二个未经测试,可能是错误的,但很接近。)

如评论中所述,根据您的数据实际 ,您可以一次性完成所有操作,而无需先取出 usernames 是什么。

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

_.uniqBy(array, 'id')