Javascript Lodash 映射并返回唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37276787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash map and return unique
提问by MindVox
I have a lodash variable;
我有一个 lodash 变量;
var usernames = _.map(data, 'usernames');
which produces the following;
产生以下结果;
[
"joebloggs",
"joebloggs",
"simongarfunkel",
"chrispine",
"billgates",
"billgates"
]
How could I adjust the lodash statement so that it only returns an array of unique values? e.g.
如何调整 lodash 语句,使其只返回一组唯一值?例如
var username = _.map(data, 'usernames').uniq();
回答by Dave Newton
Many ways, but uniq()
isn't a method on array, it's a lodash method.
很多方法,但uniq()
不是数组上的方法,而是lodash 方法。
_.uniq(_.map(data, 'usernames'))
Or:
或者:
_.chain(data).map('usernames').uniq().value()
(The second is untested and possibly wrong, but it's close.)
(第二个未经测试,可能是错误的,但很接近。)
As mentioned in the comment, depending on what your data actually is, you could do this all in one shot without first pulling out whatever usernames
is.
正如评论中提到的,根据您的数据实际是什么,您可以一次完成所有这些,而无需先拔出任何usernames
内容。
回答by Alex Trn
You can also use uniqBy
function which also accepts iteratee invoked for each element in the array. It accepts two arguments as below, where idis the iteratee parameter.
您还可以使用uniqBy
函数,该函数还接受为数组中的每个元素调用的 iteratee。它接受如下两个参数,其中id是 iteratee 参数。
_.uniqBy(array, 'id')