Sort a string date array - javascript

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;
}

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.
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
// return a.localeCompare(b); // <-- alternative
});
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
<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
// return a.localeCompare(b); // <-- alternative
});
for(var i=0; i<data.length; i++)
stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>

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:
var dateStrings = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
var sortedStrings = dateStrings.sort(function(a,b) {
var aComps = a.split("/");
var bComps = b.split("/");
var aDate = new Date(aComps[2], aComps[1], aComps[0]);
var bDate = new Date(bComps[2], bComps[1], bComps[0]);
return aDate.getTime() - bDate.getTime();
});
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:
function createSorter(dateParser) {
return function(a, b) {
var aDate = dateParser(a);
var bDate = dateParser(b);
return aDate.getTime() - bDate.getTime();
};
}
dateStrings.sort(createSorter(function(dateString) {
var comps = dateString.split("/");
return new Date(comps[2], comps[1], comps[0]);
}));
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:
function myDateParser(dateString) {
var comps = dateString.split("/");
return new Date(comps[2], comps[1], comps[0]);
}
var sortedDates = dateStrings.map(myDateParser).sort();
You can walk through the sortedDates array and if you find two non-consecutive dates, then you have dates with gaps between them.

var dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
function dmyOrdA(a, b){
a = a.replace(dateRE,"$3$2$1");
b = b.replace(dateRE,"$3$2$1");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function dmyOrdD(a, b){
a = a.replace(dateRE,"$3$2$1");
b = b.replace(dateRE,"$3$2$1");
if (a>b) return -1;
if (a <b) return 1;
return 0; }
function mdyOrdA(a, b){
a = a.replace(dateRE,"$3$1$2");
b = b.replace(dateRE,"$3$1$2");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function mdyOrdD(a, b){
a = a.replace(dateRE,"$3$1$2");
b = b.replace(dateRE,"$3$1$2");
if (a>b) return -1;
if (a <b) return 1;
return 0; }
dateArray = new Array("09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015");
var c = dateArray.sort( dmyOrdA );
console.log(c);

To sort your date string ascendingly without alteration to its value, try this:
var T = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
var sortedT = T.sort(s1,s2){
var sdate1 = s1.split('/');
var sdate2 = s2.split('/');
var date1 = s1[1]+'/'+s1[0]+'/'+s1[2];
var date2 = s2[1]+'/'+s2[0]+'/'+s2[2];
if (Date.parse(date1) > Date.parse(date2)) return 1;
else if (Date.parse(date1) < Date.parse(date2) return -1;
else return 0;
}
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 is mm/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.

Related

Get the minimum and maximum dates from JSON

There JSON:
[{"source":"2016-11-02","sourcecount":38},{"source":"2016-11-01","sourcecount":30},{"source":"2016-11-02","sourcecount":30},{"source":"2016-11-03","sourcecount":30}]
As in JavaScript to get the maximum and minimum date of it?
var array = [{"source":"2016-11-02","sourcecount":38},{"source":"2016-11-01","sourcecount":30},{"source":"2016-11-02","sourcecount":30},{"source":"2016-11-03","sourcecount":30}];
var max = null;
var min = null;
for (var i = 0; i < array.length; i++) {
var current = array[i];
if (max === null || current.source > max.source) {
max = current;
}
if (min === null || current.source < min.source) {
min = current;
}
}
document.getElementById('maxResult').innerHTML = max.source;
document.getElementById('minResult').innerHTML = min.source;
Max: <span id="maxResult"></span><br/ >
Min: <span id="minResult"></span>
You could do something like this, provided your date format is "yyyy-MM-dd".
Convert the date string to dateKey. which always follow the ascending order as the dates proceed. 20160101(Jan 1st) is always less than 20161231(Dec 31st).
Keeping that in mind, just convert the dates to dateKey and map dateKeys to the object and just extract the max and min of the dateKeys and return the actual date.
var datesArray = [{
"source": "2016-11-02",
"sourcecount": 38
}, {
"source": "2016-11-10",
"sourcecount": 30
}, {
"source": "2016-11-31",
"sourcecount": 38
}, {
"source": "2016-01-01",
"sourcecount": 30
}];
var newObject = {};
var dates = datesArray.map(function(obj) {
var regEx = new RegExp(/-/g);
//Convert date to dateKey
var dateKey = parseInt(obj.source.replace(regEx, ""), 10)
newObject[dateKey] = obj;
return dateKey;
});
console.log("Max", newObject[Math.max(...dates)].source);
console.log("Min", newObject[Math.min(...dates)].source);
The good thing is, your date is in ISO 8601 format already. You can just simply do this,
var data = [{"source":"2016-11-02","sourcecount":38},{"source":"2016-11-01","sourcecount":30},{"source":"2016-11-02","sourcecount":30},{"source":"2016-11-03","sourcecount":30}];
var dateArr = data.map(function(v) {
return new Date(v.source);
});
// Sort the date
dateArr.sort(function(a, b) {
return a.getTime() - b.getTime();
// OR `return a - b`
});
// The highest date is in the very last of array
var highestDate = dateArr[dateArr.length - 1];
// The lowest is in the very first..
var lowestDate = dateArr[0];
Or you prefer to have your original object instead, then you can do,
var data = [{"source":"2016-11-02","sourcecount":38},{"source":"2016-11-01","sourcecount":30},{"source":"2016-11-02","sourcecount":30},{"source":"2016-11-03","sourcecount":30}];
data.sort(function(a,b) {
var date1 = (new Date(a.source));
var date2 = (new Date(b.source));
return date1 - date2;
});
// highest date is '2016-11-03'
var highestDate = data[data.length - 1].source
// lowest date is '2016-11-01'
var lowestDate = data[0].source
Try this
var data = [{"source":"2016-11-02","sourcecount":38},{"source":"2016-11-01","sourcecount":30},{"source":"2016-11-02","sourcecount":30},{"source":"2016-11-03","sourcecount":30}]
function compare(a,b) {
if (new Date(a.source) < new Date(b.source))
return -1;
if (new Date(a.source) > new Date(b.source))
return 1;
return 0;
}
data = data.sort(compare);
var minDate = data[0].source;
var maxDate = data[data.length - 1].source;

Javascript: reducing down to one number

So I need to take a date and convert it into one single number by adding up each digit, and when the sum exceeds 10, I need to add up the two digits. For the code below, I have 12/5/2000, which is 12+5+2000 = 2017. So 2+0+1+7 = 10 & 1+0 = 1. I get it down to one number and it works in Firebug (output of 1). However, it is not working in a coding test environment I am trying to use, so I suspect something is wrong. I know the code below is sloppy, so any ideas or help reformatting the code would be helpful! (Note: I am thinking it has to be a function embedded in a function, but haven't been able to get it to work yet.)
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
solution("2000, December 5");
You can just use a recursive function call
function numReduce(numArr){
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend","Reducing: "+numArr.join(","));
//Using the array's reduce method to add up each number
var total = numArr.reduce(function(a,b){return (+a)+(+b);});
//Just outputting to div for demostration
document.getElementById("log").insertAdjacentHTML("beforeend",": Total: "+total+"<br>");
if(total >= 10){
//Recursive call to numReduce if needed,
//convert the number to a string and then split so
//we will have an array of numbers
return numReduce((""+total).split(""));
}
return total;
}
function reduceDate(dateStr){
var arrayDate = new Date(dateStr);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
return numReduce([d,m+1,y]);
}
alert( reduceDate("2000, December 5") );
<div id="log"></div>
If this is your final code your function is not outputting anything. Try this:
var array = [];
var total = 0;
function solution(date) {
var arrayDate = new Date(date);
var d = arrayDate.getDate();
var m = arrayDate.getMonth();
var y = arrayDate.getFullYear();
array.push(d,m+1,y);
for(var i = array.length - 1; i >= 0; i--) {
total += array[i];
};
if(total%9 == 0) {
return 9;
} else
return total%9;
};
alert(solution("2000, December 5"));
It will alert the result in a dialog.

Sorting data from json

I have code like this.
var a = JSON.parse(data);
var result = "<table><tr><th></th></tr>";
for (i = 0; i < a.DATA.length; i++) {
var test = a.DATA[i][0];
result += "<tr'><td>" + test + "</td></tr>";
}
result += "</table>"
$(".show").html(result);
With this code result is like this:
e_file.xlsx,
p_image.png,
test2.docx,
test_folder1,
test_folder2,
text_file.txt
But I need to have folders (test_folder1, test_folder2) and every future folders sorted before other files with suffix.
Thanks.
To sort an array with filenames/dirnames you can try with:
var data = ['e_file.xlsx', 'p_image.png', 'test2.docx', 'test_folder1', 'test_folder2', 'text_file.txt'];
var sorted = data.sort(function(a, b){
var pattern = /\.[a-z]+$/i,
isADir = !pattern.test(a),
isBDir = !pattern.test(b);
if (isADir && !isBDir) return -1;
if (isBDir && !isADir) return 1;
return a > b;
});
Output:
["test_folder1", "test_folder2", "e_file.xlsx", "p_image.png", "test2.docx", "text_file.txt"]
http://jsfiddle.net/dactivo/tGbYq/
The solution would be a fork on hsz's answer.
The difference is based on the json data you are using. Normally if it was an array of strings as in hsz example, you access directly one by one.
With the json you use, you have to first extract the "DATA" part, in this way: alldata["DATA"] and then in the sort function instead of comparing directly to "a" and "b", you have to establish which value to compare, because, every element of the DATA array is another array, that is why we access them with "a[0]" and "b[0]".
To solve this, you can continue to use hsz's solution, but your folder elements have "<dir>" as string in the second value, so you could use this to treat them differently.
Both solutions are OK.
var alldata={ "ERROR": "-", "DATA": [[ "e_file.xlsx", "8759"], ["test2.docx", "23794"], ["test_folder1", "<dir>"], ["test_folder2", "<dir>"], ["p_image.png", "2115194"], ["text_file.txt", "19"]]}
try{
data=alldata["DATA"];
data.sort(function(a,b)
{
/*
//THIS WOULD BE HSZ'S ANSWER
var pattern = /\.[a-z]+$/i,
isADir = !pattern.test(a[0]),
isBDir = !pattern.test(b[0]);
if (isADir && !isBDir) return -1;
if (isBDir && !isADir) return 1;
return a[0] > b[0];
*/
if (a[1]=="<dir>" && b[1]!="<dir>") return -1;
if (a[1]!="<dir>" && b[1]=="<dir>") return 1;
return a[0] > b[0];
});
var result = "<table><tr><th></th></tr>";
for (i = 0; i < data.length; i++) {
var test = data[i][0];
result += "<tr'><td>" + test + "</td></tr>";
}
result += "</table>"
}
catch(e){
alert(e);
}
$(".show").html(result);

How to sort just a single column in 2d array

I have a 2d array called dateTime[]. dateTime[count][0] contains future datetime and dateTime[count][1] contains a 4 digit value like 1234 or something.
I am trying to sort the column 0 that is dateTime[count][0] in ascending order. ( i,e, sorting the colunm 0 of the 2d array according to closest datetime from now)
Suppose my javascript 2d array is like:
dateTime[0][0] = 2/26/2013 11:41AM; dateTime[0][1] = 1234;
dateTime[1][0] = 2/26/2013 10:41PM; dateTime[1][1] = 4567;
dateTime[2][0] = 2/26/2013 8:41AM; dateTime[2][1] = 7891;
dateTime[3][0] = 3/26/2013 8:41AM; dateTime[3][1] = 2345;
I just wrote like this actually this is how I inserted value to dateTime[count][0] ; = new Date(x*1000); where x is unix time()
How I want the array to look after sorting:
dateTime[0][0] = 2/26/2013 8:41AM; dateTime[0][1] = 7891;
dateTime[1][0] = 2/26/2013 11:41AM; dateTime[1][0] = 1234;
dateTime[2][0] = 2/26/2013 10:41PM; dateTime[2][1] = 4567;
dateTime[3][0] = 3/26/2013 8:41AM; dateTime[3][1] = 2345;
please let me know how to solve this with less code.
Thanks. :)
This what I have done till now (I haven't sorted the array, also here dateTime is called timers)
function checkConfirm() {
var temp = timers[0][0];
var timeDiv = timers[0][1];
for (var i=0;i<timers.length;i++) {
if (timers[i][0] <= temp) { temp = timers[i][0]; timeDiv = timers[i][1]; }
}
if (timers.length > 0 ){ candidate(temp,timeDiv); }
}
function candidate(x,y) {
setInterval(function () {
var theDate = new Date(x*1000);
var now = new Date();
if ( (now.getFullYear() === theDate.getFullYear()) && (now.getMonth() === theDate.getMonth()) ) {
if ( (now.getDate() === theDate.getDate()) && (now.getHours() === theDate.getHours()) ) {
if ( now.getMinutes() === theDate.getMinutes() && (now.getSeconds() === theDate.getSeconds()) ) { alert("its time"); }
}
}
}, 10);
}
AT the end, I wanted to alert the user every time when the current time matches the time in the array. This is how I tried to solve the problem but this is completely wrong approach.
Use the .sort() function, and compare the dates.
// dateTime is the array we want to sort
dateTime.sort(function(a,b){
// each value in this array is an array
// the 0th position has what we want to sort on
// Date objects are represented as a timestamp when converted to numbers
return a[0] - b[0];
});
DEMO: http://jsfiddle.net/Ff3pd/

How to compare two different dates in dd/mm/yyyy format

Can anyone help me in finding the solution
i just want to compare two dates in dd/mm/yyyy format.
function compareDate(dt1 , dt2 , formatString){var returnVal = 2;
var dt1Parts;
var dt2Parts;
var dt1dd;
var dt1mm;
var dt1yyyy;
var dt2dd;
var dt2mm;
var dt2yyyy;
if(formatString == 'dd/mm/yyyy'){
dt1Parts = dt1.split('/');
dt2Parts = dt2.split('/');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}
else if(formatString == 'dd-mm-yyyy'){
dt1Parts = dt1.split('-');
dt2Parts = dt2.split('-');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}else{
alert(formatString+' format is not supported.');
}
if(dt1yyyy == dt2yyyy && dt1mm == dt2mm && dt1dd == dt2dd){
returnVal = 0;
}
else if(dt1yyyy > dt2yyyy){
returnVal = 1 ;
}else if(dt1yyyy == dt2yyyy ){
if(dt1mm > dt2mm){
returnVal = 1;
}else if(dt1mm == dt2mm){
if(dt1dd > dt2dd){
returnVal = 1;
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
return returnVal;
}
Thanks in advance,
Shilpa
Invert the strings to yyyy/mm/dd, or convert them to a number or Date object.
The simplest way just for comparison would be ASCII order. Invert using something like this:
function invert(date) {
return date.split(/[/-]/).reverse().join("")
}
function compareDates(date1, date2) {
return invert(date1).localeCompare(invert(date2));
}
Here's how you convert that string format to a date:
var myString = "17/07/1979",
correctFormat = myString.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$2/$1"),
myDate = new Date(correctFormat);
Without knowing what language or class libs you're working with:
Method 1: Resort your strings to be yyyymmdd and the do string compare.
Method 2: Stuff yyyy mm and dd into the high, middle, and low bits of an integer and compare.
The easiest way is probably to create 2 javascript Date objects from your input string. You could achieve that by chopping your input into day, month and year. You can use the 'substring' function for that.
Then you can do:
var firstDate = new Date(year1, month1, day1);
var secondDate = new Date(year2, month2, day2);
Once you have 2 date objects, you can use the normal compare operators:
if (firstDate > secondDate)
// do something
else
...
Try this
var date1=new Date('your date1 string');
var date2=new Date('your date2 string');
var difference=new Date(date1.getTime()-date2.getTime());
if ($.datepicker.parseDate('dd/mm/yy', fDate) > $.datepicker.parseDate('dd/mm/yy', tDate)) {
//do something
}
You can compare two dates.Here I compare from date greater than to date
try this

Categories

Resources