How to sort date array with javascript? - javascript

I am trying to sort the date array. It does perfectly. But May 4 is listed in the last element of the array which is wrong. Could you help me to resolve this?
var listOfString = "2016-05-24|Failed,2016-05-04|Failed,2016-04-19|Passed,2016-04-15|Passed,2016-06-01|Failed";
var arrayStrings = listOfString.split(',');
var dateArray = new Array();
var count = 0;
for (var i = 0; i < arrayStrings.length; i++) {
dateArray[count++] = new Date(arrayStrings[i].split('|')[0]);
}
dateArray.sort();
for (var i = 0; i < dateArray.length; i++) {
alert(dateArray[i]);
}
Output received as
Fri Apr 15 2016 05:30:00 GMT+0530 (India Standard Time)
Tue Apr 19 2016 05:30:00 GMT+0530 (India Standard Time)
Tue May 24 2016 05:30:00 GMT+0530 (India Standard Time)
Wed Jun 01 2016 05:30:00 GMT+0530 (India Standard Time)
Wed May 04 2016 05:30:00 GMT+0530 (India Standard Time)

Since you have the values as strings in descending order (y-m-d) and with preceding zeroes it means they are sortable also as strings. You don't need to do any conversions in this case, just sort as a string array after split.

Solution:
var listOfString = "2016-05-24|Failed,2016-05-04|Failed,2016-04-19|Passed,2016-04-15|Passed,2016-06-01|Failed";
var arrayStrings = listOfString.split(',');
var dateArray = new Array();
var count = 0;
for (var i = 0; i < arrayStrings.length; i++) {
dateArray[count++] = arrayStrings[i].split('|')[0];
}
dateArray.sort();
for (var i = 0; i < dateArray.length; i++) {
console.log(dateArray[i]);
}

Change your date.sort() to this
dateArray.sort(function(a,b) {
return a-b;
});
Returns
VM126:57 Fri Apr 15 2016 05:30:00 GMT+0530 (IST)
VM126:57 Tue Apr 19 2016 05:30:00 GMT+0530 (IST)
VM126:57 Wed May 04 2016 05:30:00 GMT+0530 (IST)
VM126:57 Tue May 24 2016 05:30:00 GMT+0530 (IST)
VM126:57 Wed Jun 01 2016 05:30:00 GMT+0530 (IST)
You assumed that .sort() would automatically handle dates but unfortunately, that's not the case. It either does alphabetical or numerical sort only and that was the result you had. To fix, I added a callback function that will determine if an item is ahead or behind in the order in the bubble sort and subtracting dates returns the number of seconds between the two dates and that would be a number and easy to subtract and return the difference in the sort.

Related

How to use .replace to replace the string in a array

need to replace GMT+0530 (India Standard Time) to IST
dynamically for multiple array list
for now my array list has 6 entries. need to replace for all the array list .
function getTimeAccordingtoTimeZone(utc){
utc = new Date(Date.parse(utc));
var dateUTC = utc ;
var dateIST = new Date(dateUTC);
//date shifting for IST timezone (+5 hours and 30 minutes)
var current_time_zone = getCurrentTimeZone();
var hour_diff = parseInt(current_time_zone);
var minute_diff = current_time_zone - hour_diff;
minute_diff = minute_diff*60;
dateIST.setHours(dateIST.getHours() + hour_diff);
dateIST.setMinutes(dateIST.getMinutes() + minute_diff);
var new_date = dateIST;
return new_date;
}
new_date returns
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
I'd propose you use moment JS to format the string.
In your case, the following code will help you:
const moment = require('moment');
date = moment();
const dateString = `${date.format('ddd MMM DD YYYY HH:mm:ss')} IST`
console.log(dateString);
MomentJs Documentation

How to check if two arrays of dates have matching items?

I have two arrays of dates. The first one have all the booked dates and the second one will have dates between "start day" and "end day" which user will pick.
Now I have to confirm that the days between the start and stop will not be found from the fully booked dates array.
I'm using Vue.js to update data.
Here is what I have done to get those dates:
/**
* Get dates from datepicker and format it to the same format that fully booked array has it's dates.
**/
var day1 = moment( this.startDate, 'DD/MM/Y').format('Y,M,D');
var day2 = moment( this.endDate, 'DD/MM/Y').format('Y,M,D');
var start = new Date(day1);
var end = new Date(day2);
/**
* Get dates between start and stop and return them in the dateArray.
**/
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
function getDates(startDate, stopDate) {
var dateArray = [];
var currentDate = startDate;
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}
var dateArray = getDates(start, end);
/**
* Set dateArray in to Vue.js data.
**/
this.$set('daysBetweenStartStop', dateArray);
/**
* Get arrays of dates from the Vue.js data. calendar = Booked dates | matchingDays = Dates between start and stop.
**/
var calendar = this.fullDates;
var matchingDays = this.daysBetweenStartStop;
/**
* #description determine if an array contains one or more items from another array.
* #param {array} haystack the array to search.
* #param {array} arr the array providing items to check for in the haystack.
* #return {boolean} true|false if haystack contains at least one item from arr.
*/
var findIfMatch = function (haystack, arr) {
return arr.some(function (v) {
return haystack.indexOf(v) >= 0;
});
};
var matching = findIfMatch(calendar, matchingDays);
/**
* Check the results. If false we are good to go.
**/
if (matching){
alert('WE FOUND A MATCH');
} else {
alert('GOOD TO GO');
}
Arrays are in the following format:
var calendar = [
Sun Oct 02 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 09 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 16 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 23 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
var matchingDays = [
Fri Oct 28 2016 00:00:00 GMT+0300 (EEST),
Sat Oct 29 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
]
My problem is that even if those two arrays have exactly same dates they will still somehow be considered as a not identical. Any ideas how to get this working?
Your match function should look like this :
findIfMatch = function (haystack, arr){
var i = 0;//array index
var j = 0;//array index
while(j < arr.length && i < haystack.length){
cur_cal = Date.parse(haystack[i]);
cur_match = Date.parse(arr[j]);
if(cur_cal > cur_match){
j++;
}else if(cur_cal < cur_match){
i++;
}else{
return true;
}
}
return false;
}
To get matching records from two array use this
var calendar = [
Sun Oct 02 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 09 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 16 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 23 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
];
var matchingDays = [
Fri Oct 28 2016 00:00:00 GMT+0300 (EEST),
Sat Oct 29 2016 00:00:00 GMT+0300 (EEST),
Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)
];
var newCalendar = [];
var newMatchingDays = []
$.map(calendar, function(date){
newCalendar.push(date.toString())
});
$.map(matchingDays, function(date){
newMatchingDays.push(date.toString())
});
var result = [];
$.map(newCalendar, function (val, i) {
if ($.inArray(val, newMatchingDays) > -1) {
result.push(val);
}
});
console.log(result);
Firstly you can't compare dates like that, Date is an object.
eg.
var d1 = new Date('2016-09-30');
var d1 = new Date('2016-09-30');
console.log(d1 === d2); // = false
You would need to loop the array and compare each item, rather than use indexOf.
or maybe use the Array.filter(). Or alternatively use and object as a lookup.
eg. If say you had ->
var calendar = {
"Sun Oct 02 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 09 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 16 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 23 2016 00:00:00 GMT+0300 (EEST)": true,
"Sun Oct 30 2016 00:00:00 GMT+0300 (EEST)": true
};
if (calendar["Sun Oct 16 2016 00:00:00 GMT+0300 (EEST)"]) {
console.log("We have date");
}
Notice how I use a string representation for the date, this could be a number too, eg. from Date.getTime().
Here is using Array.filter, I don't think it's as fast a Object lookup's. But here we go.
var calendar = [
new Date('2016-09-01'),
new Date('2016-09-12'),
new Date('2016-09-10')
];
var finddate = new Date('2016-09-12');
var found = calendar.filter(function (a) { return a.getTime() === finddate.getTime();});
And if you don't mind using third party library, try underscore..
eg.
var days = [new Date('2016-09-01'), new Date('2016-09-10'), new Date('2016-09-30')];
var finddays = [new Date('2016-09-01'), new Date('2016-09-30')];
var found = _.intersectionWith(days, finddays,
function (a,b) { return a.getTime() === b.getTime(); });

What's wrong with this javascript sort

I'm not getting the sort results I expect. What's wrong.
Here's the code:
data.sort(function(a,b){
return (Date.parse(a) - Date.parse(b));
});
for(var j = 0; j < data.length; j++){
var item = data[j];
console.log(j+") " +item.createdAt+":"+Date.parse(item.createdAt));
}
And here's the output:
0) Fri Jun 10 2016 16:58:26 GMT-0400 (Eastern Daylight Time):1465592306000
1) Tue Jun 07 2016 08:07:34 GMT-0400 (Eastern Daylight Time):1465301254000
2) Fri Jun 10 2016 15:57:44 GMT-0400 (Eastern Daylight Time):1465588664000
3) Fri Jun 10 2016 14:34:45 GMT-0400 (Eastern Daylight Time):1465583685000
4) Fri Jun 10 2016 14:22:02 GMT-0400 (Eastern Daylight Time):1465582922000
5) Fri Jun 10 2016 11:14:34 GMT-0400 (Eastern Daylight Time):1465571674000
6) Fri Jun 10 2016 10:03:56 GMT-0400 (Eastern Daylight Time):1465567436000
7) Fri Jun 10 2016 10:02:58 GMT-0400 (Eastern Daylight Time):1465567378000
8) Thu Jun 09 2016 16:32:29 GMT-0400 (Eastern Daylight Time):1465504349000
9) Thu Jun 09 2016 16:29:24 GMT-0400 (Eastern Daylight Time):1465504164000
As data is array of object and each object contains the createdAt property on which the array should be sorted, you need
data.sort(function(a, b) {
return (Date.parse(a.createdAt) - Date.parse(b.createdAt));
});
If the data is coming from server database, I'll suggest to get the data sorted on the date from the Database itself.
Tushar hit it on the head, if that is what you're looking to sort on. If you want to go further in depth about sorting on a particular value comparison you'll want to research the array prototype. You can find that here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

How to Format JavaScript Long String Date

I am using this code to export dates of current week days
var arr =[];
var curr = new Date();
var first = curr.getDate() - curr.getDay();
for (var i = 1; i < 6; i++) {
var next = new Date(curr.getTime());
next.setDate(first+1 );
arr.push(next.toString());
}
but the output looks like Mon Nov 09 2015 01:43:57 GMT-0800 (Pacific Standard Time) in the array of
["Mon Nov 09 2015 01:43:57 GMT-0800 (Pacific Standard Time)", "Mon Nov
09 2015 01:43:57 GMT-0800 (Pacific Standard Time)", "Mon Nov 09 2015
01:43:57 GMT-0800 (Pacific Standard Time)", "Mon Nov 09 2015 01:43:57
GMT-0800 (Pacific Standard Time)", "Mon Nov 09 2015 01:43:57 GMT-0800
(Pacific Standard Time)"]
Can you please let me know how I can format the date() to get only
Mon Nov 09 2015 and remove 01:43:57 GMT-0800 (Pacific Standard Time)?
Thanks
You can use the toDateString() method on the Date object.
arr.push(next.toDateString());
Its simple. I am using your code. just use toDateString() method of Date()
var arr =[];
var curr = new Date();
var first = curr.getDate() - curr.getDay();
for (var i = 1; i < 6; i++) {
var next = new Date(curr.getTime());
next.setDate(first+1 );
arr.push(next.toDateString());
}
document.write(new Date().toDateString());

Split an array of date times into sub dates in javascript

I have a simple data set that contains an array of times that are separated into 3 hour chunks:
0: Wed Dec 04 2013 12:00:00 GMT-0800 (PST)
1: Wed Dec 04 2013 15:00:00 GMT-0800 (PST)
2: Wed Dec 04 2013 18:00:00 GMT-0800 (PST)
3: Wed Dec 04 2013 21:00:00 GMT-0800 (PST)
4: Thu Dec 05 2013 00:00:00 GMT-0800 (PST)
5: Thu Dec 05 2013 03:00:00 GMT-0800 (PST)
6: Thu Dec 05 2013 06:00:00 GMT-0800 (PST)
7: Thu Dec 05 2013 09:00:00 GMT-0800 (PST)
What I need to do is loop through this array and create a new array that adds in the "missing" hours. So ideally the new array would be an array of 21 new date objects, separated out by each hour.
Edit:
Tried looping through each item in the array, and then looping through 3 times within there and try to create a new date and push it into a new array. But I'm stuck there.
After some snooping and researching some date stuff, was able to figure out what I needed to do. (open to suggestions if there are better ways to do this)
var oldArrayLength = oldArray.length;
var newArray = [];
for (var i = 0; i < oldArrayLength; i++) {
for( var j = 0; j < 3; j++ ) {
var theNewTime = new Date(oldArray[i]);
theNewTime.setHours(theNewTime.getHours() + j);
newArray.push(theNewTime);
}
}

Categories

Resources