0

I am trying to sort a array of objects by their date.

Each object has a key time:

{
    accuracy: "15.455"
    eventId: "a7e81ca3-b840-4bb1-b41f-821722da4a5b"
    humidity: "50"
    latitude: "2.708813"
    location: {accuracy: {…}, latitude: {…}, longitude: {…}}
    longitude: "102.0083215"
    name: "Tag1"
    tags: {humidityOffset: {…}, rssi: {…}, dataFormat: {…}, 
           movementCounter: {…}, updateAt: {…}, …}
    temperature: "28.26"
    time: "2020-10-18T01:46:00+0800"
}

I have tried using the following function which I made based on this question but the dates do not get sorted.

 const sortTagsByDate = (array) => {
    const stringToDate = array.map(data => new Date(data.time));
    const sortData = stringToDate.sort((a,b)=> b.time - a.time);
    return sortData;
}

When I console log the output of the function above the dates are converted to a DateTime but not sorted and only the time gets returned.

Sun Oct 18 2020 01:42:17 GMT+0800 (Malaysia Time)
Tue Oct 20 2020 23:04:51 GMT+0800 (Malaysia Time)
Sun Oct 18 2020 01:42:35 GMT+0800 (Malaysia Time)
yudhiesh
  • 3,560
  • 3
  • 7
  • 24
  • 2
    `(a,b)=> b.time - a.time` -> `(a,b)=> b - a` – VLAZ Oct 21 '20 at 15:39
  • you are returning a sorted array of dates. not a sorted array of objects. – GottZ Oct 21 '20 at 15:39
  • When the dates are subtracted, each date is converted to its `valueOf()`. No need to do it explicitly. – AlexH Oct 21 '20 at 15:41
  • Also, I believe `new Date.valueOf` will return the current timestamp if you don't initialize it with the string. – AlexH Oct 21 '20 at 15:42
  • 2
    By the way, you don't need to convert ISO 8601 formatted dates into a `Date` to compare them. Lexicographical sorting acts as chronological sorting for them. EDIT: assuming they are in the same timezone, that is. – VLAZ Oct 21 '20 at 15:42
  • Yes it is all in the same timezone. – yudhiesh Oct 21 '20 at 15:49

1 Answers1

1

Instead of b.time - a.time, try b.getTime() - a.getTime(). Here's an example:

const sortTagsByDate = (array) => {
    return array.sort((a,b)=> a.time.localeCompare(b.time));
}

let example1 = { time: "2020-10-18T01:46:00+0800" };
let example2 = { time: "2020-10-18T01:47:00+0800" };
let example3 = { time: "2020-10-18T01:48:00+0800" };
let exampleArray = [example1, example2, example3];

console.log(sortTagsByDate(exampleArray));
AlexH
  • 766
  • 4
  • 21