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 >
<div >
<div >
2022-09-24 16:10:00
</div>
</div>
<div >
<div >
2022-09-24 16:05:23
</div>
</div>
<div >
<div >
2022-09-24 16:05:22
</div>
</div>
<div >
<div >
2022-09-24 16:05:27
</div>
</div>
<div >
<div >
</div>
</div>
<div >
<div >
</div>
</div>
<div >
<div >
</div>
</div>
</div>
</div>
CodePudding user response:
There's two issues in your code. Firstly, you need to check that the .creationDate
element has content in both the a
and b
elements. Secondly you need to also return a value in the case where it doesn't, not just a plain return;
statement. In the example below I used 0
, but this can be amended to 1
or -1
as necessary for your use case.
Note in the example how clicking the 'Sort' button multiple times doesn't change the outcome.
function sortingContacts() {
$('#rgMatches .rows .GroupItem').sort((a, b) => {
let aText = $(a).find('.creationDate').text();
let bText = $(b).find('.creationDate').text();
if (aText != '' && bText != '') {
return new Date(aText) < new Date(bText) ? 1 : -1;
} else {
return 0;
}
}).appendTo('#rgMatches .rows');
}
$('button').on('click', sortingContacts);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div id="rgMatches">
<div >
<div >
<div >
2022-09-24 16:10:00
</div>
</div>
<div >
<div >
2022-09-24 16:05:23
</div>
</div>
<div >
<div >
2022-09-24 16:05:22
</div>
</div>
<div >
<div >
2022-09-24 16:05:27
</div>
</div>
<div >
<div >
</div>
</div>
<div >
<div >
</div>
</div>
<div >
<div >
</div>
</div>
</div>
</div>
<button>Sort</button>