简体   繁体   English

Javascript中基于某些键值对数组进行排序,然后根据另一个键值对数组进行再次排序

[英]array sorting in Javascript based on certain key value and sort again based on another key value

An array contains the list of values as below: 数组包含以下值列表:

    Object {status: "Pen"
    apptDate:"12-06-2001 04:00 PM "
    func:"OOS"}

  Object {status: "Pen"
    apptDate:"14-03-2001 04:00 PM "
    func:"OOS"}

    Object {status: "Pen"
    apptDate:"15-09-2001 04:00 PM "
    func:"OOS"}

 Object {status: "Pen"
    apptDate:"11-01-2001 04:00 PM "
    }

   Object {status: "Pen"
    apptDate:"10-02-2001 04:00 PM "
    }

Need to create a new array based on the current array that will have the object.func value as "OOS" should be pushed first inside the array while keeping the apptDate in asc order, incase no value present in object.func then sort the sort the array based on apptDate in asc order 需要基于当前数组创建一个新数组,该数组将具有object.func值,如“ OOS”,应首先将其推入数组,同时将apptDate保持asc顺序,以防object.func中没有值,然后对排序进行排序基于apptDate的数组,升序排列

With an ISO 8601 date string, you could use String#localeCompare , while respecting 'OOS' sorting on top. 使用ISO 8601日期字符串,您可以使用String#localeCompare ,同时注意最上面的'OOS'排序。

 var array = [{ status: "Pen", apptDate: "2001-06-12 04:00", func: "OOS" }, { status: "Pen", apptDate: "2001-03-14 04:00", func: "OOS" }, { status: "Pen", apptDate: "2001-09-15 04:00", func: "OOS" }, { status: "Pen", apptDate: "2001-01-11 04:00" }, { status: "Pen", apptDate: "2001-02-10 04:00" }]; array.sort(function (a, b) { return (b.func === 'OOS') - (a.func === 'OOS') || a.apptDate.localeCompare(b.apptDate); }); console.log(array); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can use array.sort with a comparing function such as this: 您可以将array.sort与如下比较功能一起使用:

function(a,b){
    if(a.func && a.func == "OOS" && a.func != b.func){
    return -1;
  } else {
    return new Date(a.apptDate) - new Date(b.apptDate);
  }
}

Note: I've updated some dates to make them valid. 注意:我已经更新了一些日期以使其有效。

 var arr = [{ status: "Pen", apptDate: "12-18-2001 04:00 PM ", func: "OOS" }, { status: "Pen", apptDate: "9-18-2001 04:00 PM ", func: "OOS" }, { status: "Pen", apptDate: "11-18-2001 04:00 PM ", func: "OOS" }, { status: "Pen", apptDate: "11-18-2001 04:00 PM " }, { status: "Pen", apptDate: "10-18-2001 04:00 PM " }]; arr.sort(function(a,b){ if(a.func && a.func == "OOS" && a.func != b.func){ return -1; } else { return new Date(a.apptDate) - new Date(b.apptDate); } }); console.log(arr); 

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

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