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)
6
  • 2
    (a,b)=> b.time - a.time -> (a,b)=> b - a Commented Oct 21, 2020 at 15:39
  • you are returning a sorted array of dates. not a sorted array of objects. Commented Oct 21, 2020 at 15:39
  • When the dates are subtracted, each date is converted to its valueOf(). No need to do it explicitly. Commented Oct 21, 2020 at 15:41
  • Also, I believe new Date.valueOf will return the current timestamp if you don't initialize it with the string. Commented Oct 21, 2020 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. Commented Oct 21, 2020 at 15:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Hi this works but as I mentioned I want the objects to be sorted based on the date.
Should work now. Used @VLAZ's suggestion of lexicographical sorting.
Yes it does I wanted it sorted from oldest to newest so i just changed it a bit return array.sort((a,b)=> a.time.localeCompare(b.time));
I've updated my answer. If it works, would you mind accepting the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.