0

Is it possible to concatenate two lodash methods? In my case uniqBy and sortBy

Example:

const uniquePotentialClients = _.uniqBy(
    [...potentialClients],
    uniqueContact => uniqueContact.phoneNumbers[0].number,
 );

 const sortPotentialClients = _.sortBy(
    [...potentialClients],
    uniqueContact => uniqueContact.givenName,
 );

Is it possible two apply these two methods to one collection?

lecham
  • 2,294
  • 6
  • 22
  • 41
  • 1
    https://lodash.com/docs/4.17.11#chain chain is made specifically for that – Caramiriel Mar 19 '19 at 11:21
  • 1
    Possible duplicate of [How do you chain functions using lodash?](https://stackoverflow.com/questions/35590543/how-do-you-chain-functions-using-lodash) – Caramiriel Mar 19 '19 at 11:27

1 Answers1

2

You have two choices:

Chaining

This wraps the value you'd be working on and then you can chain more operations on it without supplying a parameter. When finished .value() extracts the final value.

const result = _.chain([...potentialClients])
  .uniqBy(uniqueContact => uniqueContact.phoneNumbers[0].number)
  .sortBy(uniqueContact => uniqueContact.givenName)
  .value();

Using functional composition

const uniqFn = _.uniqBy(uniqueContact => uniqueContact.phoneNumbers[0].number);
const sortFn = _.sortBy(uniqueContact => uniqueContact.givenName);

const composedFn = _.flow(uniqFn, sortFn);

const result = composedFn([...potentialClients]);

This implementation is possible if you're using the FP release of Lodash. If you aren't, then you'd have to apply modifiers to the functions to flip the arguments and make them curried which will make them functional programming friendly, similar to what lodash/fp does. Here is a sample of how this can be done:

 //_.curry requires the arity to be declared, passing 2 satisfies both these functions
const makeFpFriendly = f => _.curry(_.flip(f), 2);

const uniqByFpFriendly = makeFpFriendly(_.uniqBy);
const sortByFpFriendly = makeFpFriendly(_.sortBy);
VLAZ
  • 26,331
  • 9
  • 49
  • 67