I want to sort an array in ascending order. The dates are in string format
["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"]
Even need a function to check whether these dates are in continuous form:
eg - Valid - ["09/06/2015", "10/06/2015", "11/06/2015"]
Invalid - ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015"]
Example code:
function sequentialDates(dates){
var temp_date_array = [];
$.each(dates, function( index, date ) {
//var date_flag = Date.parse(date);
temp_date_array.push(date);
});
console.log(temp_date_array);
var last;
for (var i = 0, l = temp_date_array.length; i < l; i++) {
var cur = new Date();
cur.setTime(temp_date_array[i]);
last = last || cur;
//console.log(last+' '+cur);
if (isNewSequence(cur, last)) {
console.log("Not Sequence");
}
}
//return dates;
}
function isNewSequence(a, b) {
if (a - b > (24 * 60 * 60 * 1000))
return true;
return false;
}
To sort your date string ascendingly without alteration to its value, try this:
The resultant array
sortedT
should be a sorted array of date string.NOTE:
Your date format is stored in
dd/mm/yyyy
but the standard date format of JavaScript ismm/dd/yyyy
. Thus, in order to parse this string to Date without using external date format library, the date string is therefore needed to be converted for compatibility during sort.You will need to convert your strings to dates, and compare those dates, if you want to sort them. You can make use of the parameter that the
sort
method accepts, in order to achieve this:In order to reduce code redundancy, and to handle different date formats, you can add an additional function that will create the comparator needed by the
sort
method:You can then use different date formatters by passing different functions to the
createSorter
call.As for your second question, you can create an (sorted) array of dates from your strings, and perform your logic on that array:
You can walk through the
sortedDates
array and if you find two non-consecutive dates, then you have dates with gaps between them.The Simple Solution
There is no need to convert Strings to Dates or use RegExp.
The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY.
Update:
A helpful comment suggested using
localeCompare()
to simplify the sort function. This alternative is shown in the above code snippet.Run Snippet to Test