简体   繁体   English

使用lodash _.sortby对具有详细信息的联系人数组进行排序,最后发送空值吗?

[英]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 我认为lodash没有办法,但是使用普通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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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