Reputation: 6819
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)
Upvotes: 0
Views: 47
Reputation: 856
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));
Upvotes: 1