Answer the question
In order to leave comments, you need to log in
Sort array with nested json object?
How to sort array object with nested json by json key date.
data = [{
"history_date": "23.05.2021, 6:52",
"history_text": "Такси в ожидании"
},
{
"history_date": "24.05.2021, 8:52",
"history_text": "Такси в ожидании"
},
{
"history_date": "25.05.2021, 9:52",
"history_text": "Такси в ожидании"
}]
data = [{
"history_date": "25.05.2021, 9:52",
"history_text": "Такси в ожидании"
},
{
"history_date": "24.05.2021, 8:52",
"history_text": "Такси в ожидании"
},
{
"history_date": "23.05.2021, 6:52",
"history_text": "Такси в ожидании"
}]
Answer the question
In order to leave comments, you need to log in
For sorting, you can pass a function to the key parameter, which will return exactly the desired sort element. To convert a date datetime.strptime specifying the format.
print(sorted(data, key=lambda x: datetime.datetime.strptime(x['history_date'], '%d.%m.%Y, %H:%M'), reverse=True))
const data = [
{
history_date: "23.05.2021, 6:52",
history_text: "Такси в ожидании"
},
{
history_date: "24.05.2021, 8:52",
history_text: "Такси в ожидании"
},
{
history_date: "25.05.2021, 9:52",
history_text: "Такси в ожидании"
}
];
data.sort((a, b) => {
//Парсим дату люто костыльнол (можно лучше использовать moment.js)
const aDateParts = a.history_date.split(/[,\s|.|:]+/);
const bDateParts = b.history_date.split(/[,\s|.|:]+/);
//От этих блоков можно избавиться, если дату форматировать в YYYY-MM-DD HH:MM:SS
const aDate = new Date();
aDate.setFullYear(aDateParts[2]);
aDate.setMonth(aDateParts[1]);
aDate.setDate(aDateParts[0]);
aDate.setHours(aDateParts[3]);
aDate.setMinutes(aDateParts[4]);
const bDate = new Date();
bDate.setFullYear(bDateParts[2]);
bDate.setMonth(bDateParts[1]);
bDate.setDate(bDateParts[0]);
bDate.setHours(bDateParts[3]);
bDate.setMinutes(bDateParts[4]);
if (aDate > bDate) return -1;
else if (bDate < aDate) return 1;
else return 0;
});
console.log(data);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question