I have the following function I am using to sort my array of divs by date -
function sortDates(arrayContent) {
arrayContent.sort(function (a, b) {
var arrDate = $(a).find("#postedDate").text().replace(" posted at: ", "");
var brrDate = $(b).find("#postedDate").text().replace(" posted at: ", "");
var aTime = arrDate.split(' ')[1];
var aDate = arrDate.split(' ')[0];
a = new Date(aDate.split('/')[2], aDate.split('/')[1] - 1, aDate.split('/')[0], aTime.split(':')[0], aTime.split(':')[1]);
var bTime = brrDate.split(' ')[1];
var bDate = brrDate.split(' ')[0];
b = new Date(bDate.split('/')[2], bDate.split('/')[1] - 1, bDate.split('/')[0], bTime.split(':')[0], bTime.split(':')[1]);
return a > b ? -1 : a < b ? 1 : 0;
});
}
Where arrayContent =
arrayContent[0] = "<div class="mHr" id="mFID">
<div id="postedDate"> posted at: <b>11/12/2015 11:12:16</b> </div>
</div>" // etc etc
This current function does work however I am looking to sort hundreds of divs and the runtime using this method is taking forever.
Current limitations are that I cannot do a date converstion before populating arrayContent and each value added to arrayContent is always a string of HTML, hence why I have to find the postedDate and then split it accordingly to create a valid date variable.
This is the best I have come up with and it works however as previously mentioned it is super slow.
I also found this question which is doing much the same as me however no faster solution.
If you want to work with hundreds of elements that is a server task. But only for test purposes, try this little sort function, it avoids the use of jQuery, avoid split methods, avoid Date class and uses regular expressions to compare two numbers instead. I've tried with a one hundred items array and it takes 29.570ms and the original function takes 996.119ms.
var reg = /^.*?(\d{2})\/(\d{2})\/(\d{4})\s(\d{2})\:(\d{2})\:(\d{2}).*$/;
function sortDates(a, b){
var numberA = Number( a.replace(reg, "$3$2$1$4$5$6") );
var numberB = Number( b.replace(reg, "$3$2$1$4$5$6") );
return numberA - numberB;
}
arrayContent.sort(sortDates);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With