Не могу корректно отсортировать дату в массиве JS
Работаю над блогом, использую сервис Firebase в котором создал Realtime database. К сожалению сортировать объекты я там не смог, по этому пришлось прибегнуть к ручной сортировке при получении данных с базы. Вначале я создал массив, куда буду помещать посты, которые прийдут по запросу:
const publicationsArray = [];
Далее я обращаюсь к базе данный чтобы достать посты
firebase.database().ref('posts/').once('value').then((snapshot) => {
//...
});
Складываю посты в массив publicationsArray
firebase.database().ref('posts/').once('value').then((snapshot) => {
snapshot.forEach((item) => {
publicationsArray.push(item.val());
});
});
Данные приходят в JSON формате, и каждый пост выглядит так:
0: {
postDate: "02.01.2021, 14:02",
postDescription: "Подготовьте продукты для капкейков на молоке...",
postId: "MFxSPILrXs",
postImage: "https://cdn.pixabay.com/photo/2016/11/18/15/40/cookies-1835414_960_720.jpg",
postHeading: "Рецепт вкусных новогодних кексов!",
postType: "education"
}
Далее идёт сортировка объектов в массиве:
publicationsArray.sort(function (a, b) {
if (a.postDate > b.postDate) {
return 1;
}
if (a.postDate < b.postDate) {
return -1;
}
return 0;
});
А после сортировки вывод на страницу:
publicationsArray.forEach(item => {
postsContainer.insertAdjacentHTML('afterbegin', `
<div class="post" data-post-id="${item.postId}" data-post-type="${item.postType}">
<div class="edit-post">
<button class="edit-button"><i class="far fa-ellipsis-h"></i></button>
<ul class="edit-menu">
<li><a href="#" class="edit-content">Редактировать пост</a></li>
</ul>
</div>
<div class="post-body">
<div class="post-image">
<img src="${item.postImage}" alt="">
</div>
<p class="post-heading">${item.postHeading}</p>
<pre class="post-text">${item.postDescription}</pre>
</div>
<div class="post-footer">
<p class="post-type">${item.postType}</p>
<p class="post-date">${item.postDate}</p>
</div>
</div>
`);
});
Всё сортируется правильно, НО вот незадача, начиная с этого года, новые посты уходят в самый низ, я так понял что что-то неладное с датой, и так оно и есть, ведь "31.12.2020, 23:40" < "02.01.2021, 14:02" получится false
Тут весь код:
const publicationsArray = [];
function getPostsFromDataBase() {
firebase.database().ref('posts/').once('value').then((snapshot) => {
snapshot.forEach((item) => {
publicationsArray.push(item.val());
});
publicationsArray.sort(function (a, b) {
if (a.postDate > b.postDate) {
return 1;
}
if (a.postDate < b.postDate) {
return -1;
}
return 0;
});
publicationsArray.forEach(item => {
postsContainer.insertAdjacentHTML('afterbegin', `
<div class="post" data-post-id="${item.postId}" data-post-type="${item.postType}">
<div class="edit-post">
<button class="edit-button"><i class="far fa-ellipsis-h"></i></button>
<ul class="edit-menu">
<li><a href="#" class="edit-content">Редактировать пост</a></li>
</ul>
</div>
<div class="post-body">
<div class="post-image">
<img src="${item.postImage}" alt="">
</div>
<p class="post-heading">${item.postHeading}</p>
<pre class="post-text">${item.postDescription}</pre>
</div>
<div class="post-footer">
<p class="post-type">${item.postType}</p>
<p class="post-date">${item.postDate}</p>
</div>
</div>
`);
});
})
Как я могу усовершенствовать, улучшить, дработать эту функцию? Нужно чтобы массив сортировал объекты согласно датам правильно. Прошу протянуть руку помощи :(
Ответы (1 шт):
Как вариант - привести строку к дате и использовать это в сортировке:
publicationsArray.sort(function (a, b) {
return new Date(b.postDate) - new Date(a.postDate);
});