How To Sort Dates With Invalid Values In JavaScript
Given the sorting function below to sort dates, this doesn't add checking for invalid date values. In return, the sorting doesn't do any effect on the data provided.
So I made a little modification to the function using isNan() for date validation which sorts the dates properly.
Usage of the function.
var DateSortWithValidation = function (a, b) { var dateA = new Date(a); var dateB = new Date(b); if (dateA < dateB) return -1; if (dateA > dateB) return 1; return 0; };
var DateSortWithValidation = function (a, b) { var dateA = new Date(a); var dateB = new Date(b); if (isNaN(dateA)) { return 1; } else if (isNaN(dateB)) { return -1 } else { if (dateA < dateB) return -1; else if (dateA > dateB) return 1; else return 0; } };
$(document).ready(function () { var dates = [ new Date('08/25/2018'), new Date('test'), new Date('09/15/2018'), new Date('-'), new Date('02/03/2018'), new Date('04/25/2018'), new Date('06/18/2018'), ]; dates.sort(DateSortWithValidation); });
Comments
Post a Comment