首页 > 解决方案 > 排序功能无法正常工作

问题描述

我在 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);
    }
});

我错过了什么吗?

标签: javascriptsorting

解决方案


您可以将没有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; }


推荐阅读