I'm trying to sort some child elements of the div #rgMatches with the class .GroupItem. Some of these child elements contain a date and time as text. For instance 2022-09-24 16:45:00. Some child elements do not contain the date & time. They should not be sorted.
With the following script it works fine. The newest item was placed at the first position. Issue: If I run the script for the second time it changes the sorting order. For instance, I have 4 items with a date. Running the script again the newest item gets position 4.
What's going wrong? Thank you for your hints
function sortingContacts() {
$('#rgMatches .rows .GroupItem').sort(function(a, b) {
if ($(a).find('.creationDate').text() != '') {
return new Date($(a).find('.creationDate').text()) < new Date($(b).find('.creationDate').text()) ? 1 : -1;
} else {
return;
}
}).appendTo('#rgMatches .rows');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div id="rgMatches">
<div class="rows">
<div class="GroupItem">
<div class="creationDate">
2022-09-24 16:10:00
</div>
</div>
<div class="GroupItem">
<div class="creationDate">
2022-09-24 16:05:23
</div>
</div>
<div class="GroupItem">
<div class="creationDate">
2022-09-24 16:05:22
</div>
</div>
<div class="GroupItem">
<div class="creationDate">
2022-09-24 16:05:27
</div>
</div>
<div class="GroupItem">
<div class="creationDate">
</div>
</div>
<div class="GroupItem">
<div class="creationDate">
</div>
</div>
<div class="GroupItem">
<div class="creationDate">
</div>
</div>
</div>
</div>