[英]Sort json data on basis of date using javascript
let array=[
{
"id": "a572963a1bcd0550c4cf8518624bcb92",
"type": "car",
"created": "2022-01-18 12:47:08"
},
{
"id": "b84eb0fe1bc10550c4cf8518624bcb59",
"type": "car",
"created": "2022-01-18 06:23:39"
},
{
"id": "a95b65fc1b898110c4cf8518624bcbee",
"type": "bike",
"created": "2022-01-12 04:30:16"
},
{
"id": "5963929c1b018dd0c4cf8518624bcbc9",
"type": "bike",
"created": "2022-01-10 18:08:19"
},
{
"id": "515b65fc1b898110c4cf8518624bcb91",
"type": "bus",
"created": "2022-01-12 04:30:16"
},
{
"id": "7863929c1b018dd0c4cf8518624bcb52",
"type": "bus",
"created": "2022-01-10 18:08:17"
}
]
我想根據創建的 JSON 中可用的日期對上述 JSON 數組中的數據進行排序。 僅選擇最新創建的數據。
array.sort((a,b) => a.created > b.created ? 1 : -1)
如果創建的日期字符串格式相同,這應該可以工作
按日期屬性對項目進行排序:信用
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
然后:
array.shift();
您可以使用 sort function 根據日期值對其進行排序。 一個班輪代碼將如下所示
let sortedArray = array.sort((a, b)=> (new Date(b.created) - new Date(a.created)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.