简体   繁体   中英

How to sort an array of objects by the date that are in string form?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM