Sort array of objects with date field by date

后端 未结 5 789
猫巷女王i
猫巷女王i 2021-01-31 03:10

Give the following array of objects, I need to sort them by the date field ascending.

var myArray = [
  {
    name: \"Joe Blow\",
    date: \"Mon Oct 31 2016 00:         


        
5条回答
  •  不思量自难忘°
    2021-01-31 03:41

    Here's a solution using standard Javascript by converting both values to date object and comparing their value.

    myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
    

    A complete snippet:

    var myArray = [
      {
        name: "Joe Blow",
        date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"
      },
      {
        name: "Sam Snead",
        date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"
      },
      {
        name: "John Smith",
        date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"  
      }
    ];
    
    myArray.sort((d1, d2) => new Date(d1.date).getTime() - new Date(d2.date).getTime());
    
    console.log(myArray);

提交回复
热议问题