Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  119] [ 2]  / answers: 1 / hits: 6163  / 6 Years ago, wed, september 12, 2018, 12:00:00

I have a users object am trying to use the lodash map() method on it to have it return only the userIds, while filtering out any users with the currentUserId. I wanted to avoid using chain() since it pulls in the entire library, so it seemed that the flow() method is perfect, yet it's not mapping to an array of Id's.


import {
map, filter, flow,
} from 'lodash';

const users = {
123: {
uid: 123
},
456: {
uid: 456
}
};

const currentUserId = 123;

const userIds = flow(
map(user => user.uid),
filter(userId => userId !== currentUserId),
)(users);

Unfortunately, this is returning the same object as was passed into it. How can I get an array with the ids of all the users that are not the current user?


More From » lodash

 Answers
9

The answer applies for the standard version of lodash. Please see @Vlaz's answer for a look at the functional programming version of lodash.






When you write _.map(user => user.uid) it is actually invoking the function at that time. What you're really attempting to do is to create function that is similar to _.map, but has one of its arguments already set.



Fortunately, Lodash has a built-in to handle this situation - _.partialRight



const userIds = _.flow(
_.partialRight(_.map, user => user.uid)
_.partialRight(_.filter, userId => userId !== currentUserId),
)(users);


Documentation






Alternatively if you wish to use plain JS rather than importing a new function, you can simply wrap it in an anonymous function to pass the arguments properly.



const userIds = _.flow(
(users) => _.map(users, user => user.uid),
(users) => _.filter(users, userId => userId !== currentUserId),
)(users);

[#11346] Tuesday, September 11, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
matteo

Total Points: 81
Total Questions: 100
Total Answers: 96

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
matteo questions
Tue, Mar 8, 22, 00:00, 2 Years ago
Sun, May 31, 20, 00:00, 4 Years ago
Thu, Mar 12, 20, 00:00, 4 Years ago
Tue, Jan 22, 19, 00:00, 5 Years ago
Sun, Jul 29, 18, 00:00, 6 Years ago
;