javascript - 排序功能无法正常工作
问题描述
我在 contactArray 变量中有以下结果数组。这里我需要的是我需要按特定记录的 LastModifiedDate 对以下记录进行排序。
在前端我有 3 条记录,第一次我只选择一条记录并在后端进行一些操作,然后按 Asc 顺序再次显示到前端。
(3) [{…}, {…}, {…}]
0: {Id: "0034E00000nNLPfQAO", Name: "Test Contact 1"}
1: {Id: "0034E00000nNLTbQAO", Name: "Test Contact 2", LastModifiedDate: "2019-03-28T09:53:00.000Z", Status__c: "Pending", Status_Reason__c: undefined}
2: {Id: "0034E00000nP8VuQAK", Name: "Test Contact 3"}
使用下面的代码片段, sortedArray 如下所示,
(3) [{…}, {…}, {…}]
0: {Id: "0034E00000nNLTbQAO", Name: "Test Contact 2", LastModifiedDate: "2019-03-28T09:53:00.000Z", Status__c: "Pending", Status_Reason__c: undefined}
1: {Id: "0034E00000nNLPfQAO", Name: "Test Contact 1"}
2: {Id: "0034E00000nP8VuQAK", Name: "Test Contact 3"}
第二次尝试我从前端选择了另一个未选择的记录,
(3) [{…}, {…}, {…}]
0: {Id: "0034E00000nNLPfQAO", Name: "Test Contact 1", LastModifiedDate: "2019-03-28T09:59:13.000Z", Status__c: "Pending", Status_Reason__c: undefined}
1: {Id: "0034E00000nNLTbQAO", Name: "Test Contact 2", LastModifiedDate: "2019-03-28T09:53:00.000Z", Status__c: "Pending", Status_Reason__c: undefined}
2: {Id: "0034E00000nP8VuQAK", Name: "Test Contact 3"}
排序后的数组如下所示,
(3) [{…}, {…}, {…}]
0: {Id: "0034E00000nNLPfQAO", Name: "Test Contact 1", LastModifiedDate: "2019-03-28T09:59:13.000Z", Status__c: "Pending", Status_Reason__c: undefined}
1: {Id: "0034E00000nNLTbQAO", Name: "Test Contact 2", LastModifiedDate: "2019-03-28T09:53:00.000Z", Status__c: "Pending", Status_Reason__c: undefined}
2: {Id: "0034E00000nP8VuQAK", Name: "Test Contact 3"}
以下是我用来对数组进行排序的代码片段,
var sortedContactArray = contactArray.sort(function(obj1, obj2) {
var tc1RefUndefined = obj1.LastModifiedDate == null ? 1 : 0;
var tc2RefUndefined = obj2.LastModifiedDate == null ? 1 : 0;
if (tc1RefUndefined || tc2RefUndefined) {
return new Date(tc1RefUndefined) - new Date(tc2RefUndefined);
}
});
我错过了什么吗?
解决方案
您可以将没有LastModifiedDate
属性(或任何虚假值)的项目移动到底部,然后按字符串对ISO 8601日期进行排序。
var array = [{ Id: "0034E00000nNLPfQAO", Name: "Test Contact 1", LastModifiedDate: "2019-03-28T09:59:13.000Z", Status__c: "Pending", Status_Reason__c: undefined }, { Id: "0034E00000nNLTbQAO", Name: "Test Contact 2", LastModifiedDate: "2019-03-28T09:53:00.000Z", Status__c: "Pending", Status_Reason__c: undefined }, { Id: "0034E00000nP8VuQAK", Name: "Test Contact 3" }];
array.sort(({ LastModifiedDate: a }, { LastModifiedDate: b }) =>
!a - !b || (a || '').localeCompare(b || ''));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- java - 在随机位置具有指定数字的 Arraylist
- javascript - 带 python 和烧瓶的装载机
- integer - 在没有双精度的情况下有效地确定一个点是在三角形内部还是在边缘上
- haskell - 更适合阅读 Haskell 中的科学记数法
- python - 如何从字典转换列表
- html - 缩小浏览器时在部分内容上显示响应式页脚
- c - 我如何使用指针在这个数组(函数)内部移动而不是数组订阅
- ruby-on-rails - 如何在 Rails 中每隔几秒运行 10 分钟?
- java - 检索类类型,并实例化一个新的相同类型
- javascript - 使用 REST API 创建内容版本后打开 Salesforce 文件时出错