简体   繁体   中英

Use lodash _.sortby to sort an array of contacts with details and send null values last?

I have an array of contacts with details such as email, phone#, etc. These contacts are all sorted by name. However, while every contact must have these details, they do not always have a Name assigned. Is there a simple argument I can add to send these contacts with a null Name value to the end of the list? What I have now.

array=_.sortBy(array,'Name');
return array;

You could use a function in the iteratees for sorting falsy values to bottom.

 var users = [{ name: null }, { name: 'susan' }, { name: 'barney' }, { name: 'fred' }, { name: 'jane' }, { name: null }]; console.log(_.sortBy(users, [({ name }) => name === null, 'name'])); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script> 

I don't think there's a way for lodash, but it's easy enough with plain js

 let arr = [{ name: null }, { name: 'foo' }, { name: 'bar' }, { name: null }]; arr.sort((a, b) => a.name === null ? Number.MAX_SAFE_INTEGER : a.name.localeCompare(b.name)); console.log(arr); 

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