Lodash map and return unique
Asked Answered
T

3

38

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();
Tripersonal answered 17/5, 2016 at 12:52 Comment(2)
have you tried uniqBy? _.uniqBy(data, 'username')Octachord
I wish the data could let me do that... but on this occasion, I can't.Tripersonal
P
88

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.

Plainsong answered 17/5, 2016 at 12:58 Comment(3)
Thanks, although I mentioned something lodash specific. I am aware about uniq() being lodash.Tripersonal
@KarlBateman Right, but you're trying to call a lodash method on an array. That's not how lodash works; it doesn't modify prototypes.Plainsong
Thanks for this, more concisely _(data).map('usernames').uniq().value();Sporulate
B
19

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')
Burwell answered 24/7, 2019 at 7:7 Comment(1)
You need one more step: _.map(_.uniqBy(array, 'id'), 'id') (If the number of duplicates is ginormous and the objects are small, this approach might be more performant than the accepted answer because the intermediary array will be shorter).Illimani
P
0

very simple solution:

_.uniq(array.map(({ status }) => status))
Penrod answered 20/11, 2023 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.