简体   繁体   中英

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')))

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> 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM