R
R
rustam9ksenov2021-05-28 09:22:03
Python
rustam9ksenov, 2021-05-28 09:22:03

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": "Такси в ожидании"
    }]

To end up with the same array, only sorted by date

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

2 answer(s)
O
o5a, 2021-05-28
@rustam9ksenov

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

A
Anton Neverov, 2021-05-28
@TTATPuOT

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 question

Ask a Question

731 491 924 answers to any question