Lodash map and return unique

狂风中的少年 提交于 2020-01-12 06:32:51

问题


I have a lodash variable;

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.

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

回答1:


Many ways, but uniq() isn't a method on array, it's a lodash method.

_.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.




回答2:


You can also use uniqBy function which also accepts iteratee invoked for each element in the array. It accepts two arguments as below, where id is the iteratee parameter.

_.uniqBy(array, 'id')


来源:https://stackoverflow.com/questions/37276787/lodash-map-and-return-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!