[英]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.当我控制台记录上面函数的输出时,日期被转换为 DateTime 但没有排序并且只返回时间。
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()
.而不是b.time - a.time
,尝试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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.