I have an array of objects similar to...

[
  {
    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"
  }
]

I need to sort this list based on the most recent dates.

Based on similar problems I have seen this is my code for the solution, the array is being passed in as the records argument...

function sortRecords (records) {

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

  return sorted;

}

Can anyone advise on why this is not working? I am just getting back the same unsorted array....

share|improve this question

That's because your date String can't be parsed as a valid date, you'd need to rearrange the string you are passing to new Date(). For example the following would produce a parsable date:

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

which you then can use

function sortRecords (records) {

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

  return sorted;

}
share|improve this answer
1  
Just missing a + to concat strings in your function – Alberto Centelles 23 mins ago
    
@AlbertoCentelles thanks, Edited the answer – baao 22 mins ago

try this

    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);

Produces below output: enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.