根据日期对对象数组进行排序

时间:2016-12-03 16:04:56

标签: javascript arrays sorting javascript-objects

我有一个类似于......的对象数组。

[
  {
    date: "26/11/2016"
    hourlyRate: 50
    hoursWorked: 10
    name: "Mr G"
    natInsNumber: "GG845893G"
  },
  {
    date: "14/10/2016"
    hourlyRate: 50
    hoursWorked: 10
    name: "Mr A"
    natInsNumber: "GG845893G"
  },
  {
    date: "11/09/2016"
    hourlyRate: 50
    hoursWorked: 10
    name: "Mr H"
    natInsNumber: "GG845893G"
  },
  {
    date: "26/10/2016"
    hourlyRate: 50
    hoursWorked: 10
    name: "Mr L"
    natInsNumber: "GG845893G"
  }
]

我需要根据最近的日期对此列表进行排序。

基于类似的问题,我看到这是我的解决方案的代码,数组作为records参数传递...

function sortRecords (records) {

  var sorted = records.sort(function(a, b){
    return new Date(a.date) - new Date(b.date); 
  });

  return sorted;

}

任何人都可以建议为什么这不起作用?我只是回到同样的未排序数组....

3 个答案:

答案 0 :(得分:3)

那是因为您的日期字符串无法解析为有效日期,您需要重新排列传递给new Date()的字符串。例如,以下内容将生成可解析的日期:

function rearrangeDate(dateString) {
    var r = dateString.split('/');
  return r[1] + "/" + r[0] + "/" + r[2];
}

然后你可以使用

function sortRecords (records) {

  var sorted = records.sort(function(a, b){
    return new Date(rearrangeDate(a.date)) - new Date(rearrangeDate(b.date)); 
  });

  return sorted;

}

答案 1 :(得分:2)

试试这个

    let sorted = 
     [{
        date: "26/11/2016",
        hourlyRate: 50,
        hoursWorked: 10,
        name: "Mr G",
        natInsNumber: "GG845893G"
    },
    {
        date: "14/10/2016",
        hourlyRate: 50,
        hoursWorked: 10,
        name: "Mr A",
        natInsNumber: "GG845893G"
    },
    {
        date: "11/09/2016",
        hourlyRate: 50,
        hoursWorked: 10,
        name: "Mr H",
        natInsNumber: "GG845893G"
    },
    {
        date: "26/10/2016",
        hourlyRate: 50,
        hoursWorked: 10,
        name: "Mr L",
        natInsNumber: "GG845893G"
    }
];

function CreateDate(dateString) {
    var arr = dateString.split('/');
    return new Date(arr[2] , arr[1], arr[0]);
}

function sortRecords(records) {    
    var sorted = records.sort(function (a, b) {        
        return CreateDate(a.date) > CreateDate(b.date);
    });
    console.log(sorted);
}

sortRecords(sorted);

产生以下输出: enter image description here

答案 2 :(得分:0)

您还可以通过撤消当前日 - 月 - ,在年 - 月 - 日的基础上对日期进行排序:



var list = [
  {
    date: "26/11/2016",
    hourlyRate: 50,
    hoursWorked: 10,
    name: "Mr G",
    natInsNumber: "GG845893G"
  },
  {
    date: "30/10/2016",
    hourlyRate: 50,
    hoursWorked: 10,
    name: "Mr A",
    natInsNumber: "GG845893G"
  },
  {
    date: "11/09/2016",
    hourlyRate: 50,
    hoursWorked: 10,
    name: "Mr H",
    natInsNumber: "GG845893G"
  },
  {
    date: "26/10/2016",
    hourlyRate: 50,
    hoursWorked: 10,
    name: "Mr L",
    natInsNumber: "GG845893G"
  }
]
var result = list.sort((a,b) => a.date.split("/").reverse().join("") - b.date.split("/").reverse().join(""));
console.log(result);