kyserslick
kyserslick

Reputation: 591

Better and more performant than lodash chain

I read on some forums that lodash chain should be avoided when possible for better performances and readability of code. So is there a way to use native javascript functions on collection to replace this code.

_(userCollection).chain()
        .map('name')
        .compact()
        .uniq()
        .value();

Something like this bellow, but I' not sure that it gives any added value to write it like so

_.uniq(_.compact(userCollection.map('name')))

Upvotes: 1

Views: 4814

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

You can use _.flow() to run a sequence of methods:

const { flow, partialRight: pr, map, compact, uniq } = _;

const getUniqeNames = flow(
  pr(map, 'name'),
  compact,
  uniq
);

const arr = [{ name: 'John' }, {}, { name: 'Smith' }, {}, { name: 'John' }, { name: 'Smith' }] 

const result = getUniqeNames(arr);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

Flow works better with lodash/fp, since the methods are iteratee-first and data-last. This saves the need to partial right every method that requires an argument (pr(map, 'name') in the lodash example).

const { flow, map, compact, uniq } = _;

const getUniqeNames = flow(
  map('name'),
  compact,
  uniq
);

const arr = [{ name: 'John' }, {}, { name: 'Smith' }, {}, { name: 'John' }, { name: 'Smith' }] 

const result = getUniqeNames(arr);

console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

Upvotes: 7

Remco Haszing
Remco Haszing

Reputation: 7809

I believe this is what you're looking for. No lodash needed.

lodash.map can be changed to Array.prototype.map

lodash.compact can be changed to Array.prototype.filter

lodash.uniq can be changed to a Set constructor and optionally be converted to an Array again.

const users = [
  {name: 'Me'},
  {name: 'Someone Else'},
  {name: 'Someone Else'},
  {name: ''},
];

const uniqueNames = Array.from(new Set(users
  .map(user => user.name)
  .filter(name => name)));

console.log(uniqueNames);

Upvotes: 2

Related Questions