I have an array of arrays which the first field is a date (in string format). I want to sort them by the date (asceding), so I can use it for further calculations.
I identify two tasks on my problem. First, parse strings as dates and then sort.
a = new Date(Date.parse('1/11/2014 13:42:54'));
console.log(a)
Return 11th of January whereas I need 1st of November
Then, I the sorting should work like this:
function compare(a,b) {
if (a[0] < b[0])
return -1;
if (a[0] > b[0])
return 1;
return 0;
}
myarray.sort(compare);
So, how can I solve the problem with the dates to make it works on sorting function?
If your dates are in ISO format you can use such a code:
myarray.sort(function (a, b) {
return (new Date(a[0])).getTime() - (new Date(b[0])).getTime();
});
Just capture the date and month part, swap them and do Date.parse and new Date, like this
function getFormattedDate(dateString) {
var result = dateString.replace(/(\d+)\/(\d+)(.*)/, function (m, g1, g2, g3) {
return g2 + "/" + g1 + g3;
});
return new Date(Date.parse(result));
}
console.log(getFormattedDate('1/11/2014 13:42:54'));
// Sat Nov 01 2014 13:42:54 GMT+0000 (GMT)
Here, the regular expression, (\d+)\/(\d+)(.*) will capture three parts of the string, first (\d+) captures the date part followed by / (escaped as \/) and the month part with another (\d+) and the rest of the string is captured with (.*). Then we return a new string by swapping the positions of g2 and g1 (month and date part).
Note: If all you are trying to do is sorting, then you don't need to create a new Date object. You can simply use the result of Date.parse which is epoch time, like this
function getEpochTime(dateString) {
var result = dateString.replace(/(\d+)\/(\d+)(.*)/, function (m, g1, g2, g3) {
return g2 + "/" + g1 + g3;
});
return Date.parse(result);
}
function comparator(firstDate, secondDate) {
return getEpochTime(firstDate) - getEpochTime(secondDate);
}
and then sort like this
var arr = ['3/11/2014 13:42:54',
'2/11/2014 13:42:54',
'1/12/2014 13:42:54',
'1/11/2014 13:43:54'
];
arr.sort(comparator);
console.log(arr);
would give you
[ '1/11/2014 13:43:54',
'2/11/2014 13:42:54',
'3/11/2014 13:42:54',
'1/12/2014 13:42:54' ]
With moment.js you can create a moment object using the String+Format constructor
moment('1/11/2014 13:42:54', 'DD/MM/YYYY HH:mm:ss')
so, if you have an array of arrays which the first field is a date (in string format):
array_of_arrays = [
['1/11/2014 13:42:54', 'val'],
['2/11/2014 13:42:54', true]
];
for(array in array_of_arrays){
epoch = moment(array.shift,'DD/MM/YYYY HH:mm:ss').unix();
array.unshift(epoch);
}
now, you can just do new Date(epoch) as instead of complex date objects, we have Unix Epoch which can be easily sorted with inbuid Array.sort something like this
function Comparator(a,b){
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
}
array_of_arrays.sort(Comparator);
so now you have array_of_arrays sorted as per date
Lastly, if you need more precise answer than this, please share some more sample code.
This is problem:
a = new Date(Date.parse('1/11/2014 13:42:54'));
console.log(a)
Return 11th of January whereas I need 1st of November`
Your date format is dd/mm/yyy; Date.parse('1/11/2014 13:42:54') accepts mm/dd/yyyy
Try a date parsing as following:
function parseDate(str) {
var ds = str.match(/(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)/);
// Convert to format: mm/dd/yyyy
return new Date(ds[3], ds[2] - 1, // month is 0-based
ds[1], ds[4], ds[5], ds[6]);
}
var arr = [parseDate('3/11/2014 13:42:54'),
parseDate('2/11/2014 13:42:54'),
parseDate('1/12/2014 13:42:54'),
parseDate('1/11/2014 13:43:54')
];
arr.sort();
Or:
function parseDate(str) {
var ds = str.match(/(\d+)\/(\d+)\/(\d+)\s+(\d+):(\d+):(\d+)/);
// Convert to format: mm/dd/yyyy
return new Date(ds[3], ds[2] - 1, // month is 0-based
ds[1], ds[4], ds[5], ds[6]);
}
var arr = ['3/11/2014 13:42:54',
'2/11/2014 13:42:54',
'1/12/2014 13:42:54',
'1/11/2014 13:43:54'
];
arr.sort(function(a, b) {
return parseDate(a) - parseDate(b);
})
Related
For the following Month/Day/Year datestring array...
const array1 = ["05/31/2022", "06/01/2022", "06/02/2022"]
...I am attempting to configure the array to slice and remove all datestring array items (starting with 01 as Day) if they follow after datestring array items with 31 as Day. Same goes for instances of Day 30 followed by Day 01.
To handle this, I set up a for statement to loop through all of the strings in the array. I then used a split method to remove "/" from each array item, thus breaking MM,DD,YYYY into separate variables.
for (let i = 0; i < array1.length; i++) {
var [month, day, year] = array1[i].split('/');
console.log(month, day, year)
}
My intention for the next step is to set up a conditional that checks if an array item that includes 30 or 31 as "day" is followed by an array item that includes 01 as "day", then use slice to remove subsequent dates faster 30th or 31st. For this part, I attempted to re-consolidate month, day and year into individual array items, like so:
const newArray = []
for (let i = 0; i < array1.length; i++) {
var [month, day, year] = array1[i].split('/');
newArray.push(month + day + year)
console.log(newArray)
}
with output:
['05312022', '06012022', '06022022']
However, I'm not sure how to set up a conditional that checks if an array item that includes 30 or 31 as "day" is followed by an array item that includes 01 as "day". How can I go about the functionality for such a check?
You can loop over the dates array and grab the currDay and prevDay and if the condition is satisfied, slice the dates array and return it.
const solution = (dates) => {
for (let i = 1; i < dates.length; i++) {
const currDay = dates[i].slice(3, 5);
const prevDay = dates[i - 1].slice(3, 5);
if ((currDay === "01") & (prevDay === "31" || prevDay === "30")) {
return dates.slice(0, i);
}
}
return dates;
};
console.log(solution(["05/31/2022", "06/01/2022", "06/02/2022"]));
The following us es Array#reduce to
retain all elements unless
the number of elements retained equals the index being considered and the current element has date 01 and follows a 30 or a 31
if index in consideration is greater than the number of items retained, meaning at least one element has been skipped, then the current element is skipped as well.
const array1 = ["05/31/2022", "06/01/2022", "06/02/2022"],
output = array1.reduce(
(prev,cur,i) =>
prev.length && ["30","31"].includes( prev.slice(-1)[0].slice(3,5) ) &&
(prev.length === i && cur.slice(3,5) === "01" || i > prev.length) ?
prev :
[...prev, cur],
[]
);
console.log( output );
I have an array of date ranges(selectedRanges) which shows assigned dates for a member between the main date range. I want to know the date ranges where he/she is unassigned. Please refer to the below example.
mainDateRange = ['01-01-2020', '14-06-2020'];
selectedRanges = [
['03-01-2020','04-01-2020'],
['03-01-2020','05-01-2020'], //overlapping dates
['11-01-2020','13-01-2020'],
['01-02-2020','20-02-2020'],
['15-03-2020','18-03-2020'],
['06-01-2020','06-01-2020'], //date ranges will not be ordered
['03-01-2020','04-01-2020']
]; //dates that the member has work assigned
Desired output
excludedRanges = [
['01-01-2020','02-01-2020'],
['07-01-2020','10-01-2020'],
['14-01-2020','31-01-2020'],
['21-02-2020','14-03-2020'],
['19-03-2020','14-06-2020']
]; //shows all the unassigned periods(ranges)
selectedRanges date ranges will have ranges in random order and also may have duplicate and overlapping dates.
I have searched a lot and found nothing. I am only able to get the unselected dates, not as a range. Please help.
Thank you
Interesting problem, I'll propose an approach to achieve this desired behavior by doing the following:
Transform all string dates into date objects.
Sort the selectedRanges array in ascending order using the start and end dates. This sorting step is cricual to finding the date range gaps.
Adding a "moving cursor" date that moves between the mainDateRange to find and add the missing ranges to the output array.
Before we start the date calculations, we'll need a few helper functions. I've added two functions to go back and forth between the date object and the string format you have (dd-mm-yyyy). Please note that you may not need these two helper function if you use something like Moment.js, but I won't impose an extra dependency on your project.
function stringToDate(stringDate) {
const parts = stringDate.split('-').map((p) => parseInt(p));
parts[1] -= 1;
return new Date(...parts.reverse());
}
function dateToString(date) {
return `${('0' + date.getDate()).slice(-2)}-${('0' + (date.getMonth() + 1)).slice(-2)}-${date.getFullYear()}`;
}
I've also added a sorter function that makes sure the ranges are sorted in an ascending fashion (smaller ranges first).
function dateRangeSorter(a, b) {
if (a[0] < b[0]) return -1;
else if (a[0] > b[0]) return 1;
if (a[1] < b[1]) return -1;
else if (a[1] > b[1]) return 1;
return 0;
}
Now we're good to go on the calculation, here is a code snippet that will log the output at the end.
// data
const output = [];
const oneDayInMs = 24 * 60 * 60 * 1000;
const mainDateRange = ['01-01-2020', '14-06-2020'];
const selectedRanges = [
['03-01-2020','04-01-2020'],
['03-01-2020','05-01-2020'],
['11-01-2020','13-01-2020'],
['01-02-2020','20-02-2020'],
['15-03-2020','18-03-2020'],
['06-01-2020','06-01-2020'],
['03-01-2020','04-01-2020']
];
// helpers
function stringToDate(stringDate) {
const parts = stringDate.split('-').map((p) => parseInt(p));
parts[1] -= 1;
return new Date(...parts.reverse());
}
function dateToString(date) {
return `${('0' + date.getDate()).slice(-2)}-${('0' + (date.getMonth() + 1)).slice(-2)}-${date.getFullYear()}`;
}
function dateRangeSorter(a, b) {
if (a[0] < b[0]) return -1;
else if (a[0] > b[0]) return 1;
if (a[1] < b[1]) return -1;
else if (a[1] > b[1]) return 1;
return 0;
}
// transform into date and sort
const mainDateRangeAsDates = mainDateRange.map(stringToDate);
const selectedRangesAsDates = selectedRanges.map((range) => (range.map(stringToDate)))
.sort(dateRangeSorter);
// start at the beginning of the main date range
let movingDate = mainDateRangeAsDates[0];
// loop through the selected ranges
selectedRangesAsDates.forEach(([startDate, endDate]) => {
// if there's a gap, add it to the output
if (movingDate < startDate) {
output.push([
dateToString(movingDate),
dateToString(new Date(startDate.getTime() - oneDayInMs))
]);
}
// move the cursor date to one day after the end of current rage
movingDate = new Date(endDate.getTime() + oneDayInMs);
});
// if there is a gap at the end, add it as well
if (movingDate < mainDateRangeAsDates[1]) {
output.push([
dateToString(movingDate),
dateToString(mainDateRangeAsDates[1])
]);
}
console.log(output);
Used a similar approach to this: How to make sure every number of a bigger range is within some smaller ranges?
Convert all strings to Dates. Sorts by minimum of range.
Moves minimum position forward, until it finds a gap, and pushes to res array.
Pushes range from last minimum to maximum if it exists
mainDateRange = ['01-01-2020', '14-06-2020'];
selectedRanges = [
['03-01-2020', '04-01-2020'],
['03-01-2020', '05-01-2020'], //overlapping dates
['11-01-2020', '13-01-2020'],
['01-02-2020', '20-02-2020'],
['15-03-2020', '18-03-2020'],
['06-01-2020', '06-01-2020'], //date ranges will not be ordered
['03-01-2020', '04-01-2020']
]; //dates that the member has work assigned
function gapFinder(mainDateRange, selectedRanges) {
const dateToInt = a => new Date(a.split('-').reverse().join('-'))
const intToDate = a => new Date(a).toISOString().slice(0, 10).split('-').reverse().join('-')
// convert to numbers
selectedRanges = selectedRanges.map(r => r.map(dateToInt))
// presort ranges
selectedRanges.sort(([a, ], [b, ]) => a - b)
let [min, max] = mainDateRange.map(dateToInt)
const res = []
for (const [x, y] of selectedRanges) {
if (min > max) break
if (min < x)
res.push([min, x.setDate(x.getDate() - 1)])
min = Math.max(min, y.setDate(y.getDate() + 1))
}
if (min <= max) res.push([min, max])
return res.map(r => r.map(intToDate))
}
console.log(JSON.stringify(gapFinder(mainDateRange,selectedRanges)))
selectedRanges.push(['11-06-2020', '13-06-2020'])
console.log(JSON.stringify(gapFinder(mainDateRange,selectedRanges)))
I have this code:
<script type="text/javascript">
function abc(objarray) {
objarray = objarray.sort(function (a, b) { return new Date(a).getTime() - new Date(b).getTime() });
alert(objarray);
}
objarray = ["16.08.1993 11:13", "16.08.1994 11:12", "13.08.1994 11:12", "13.08.1996 10:12", "08.08.1996 10:12"];
abc(objarray);
</script>
Date time format: dd.MM.yyyy HH:MM
I want to sort so that I can get the latest date first, but its not working.
You need to switch a and b and take another string for comparing, like
1993-08-16 11:13
the ISO 6801 data and time format, wich is comparable with String#localeCompare.
function abc(objarray) {
objarray = objarray.sort(function(a, b) {
function getISO(s) {
return s.replace(/(..).(..).(....) (.....)/, '$3-$2-$1 $4');
}
return getISO(b).localeCompare(getISO(a));
});
}
var objarray = ["16.08.1993 11:13", "16.08.1994 11:12", "13.08.1994 11:12", "13.08.1996 10:12", "08.08.1996 10:12"];
abc(objarray);
console.log(objarray);
Try this:
String.prototype.getCorrectDate = function () {
var date = this.split(' ')[0];
var hours = this.split(' ')[1];
var dateSplitted = date.split('.');
return new Date(dateSplitted[2] + '.' + dateSplitted[1] + '.' + dateSplitted[0] + ' ' + hours);
};
var dates = ["16.08.1993 11:13", "16.08.1994 11:12", "13.08.1994 11:12", "13.08.1996 10:12", "08.08.1996 10:12"];
var sorted = dates.sort(function(a, b) {
return b.getCorrectDate() - a.getCorrectDate();
});
alert('First from sorted: '+ sorted[0]);
alert('Last from sorted: '+ sorted[sorted.length - 1]);
https://jsfiddle.net/Lcq6wqhb/
Javascript's native method sort is used to sorting arrays, and we can pass callback function let's say sorting behavior(Sorting an array of JavaScript objects).
But before sorting we need to transform date strings to correct format, to be accepted new Date(dateString) as parameter, otherwise it gives error Invalid Date.
I'm transorming dd.mm.yyyy hh:MM to yyyy.mm.dd HH:MM using getCorrectDate method
I have an array with the following values (example):
[
1491408000000,
1491494400000,
1491753600000,
1493222400000,
1493308800000,
1493568000000
]
Where the index is a date time. The date time will always be at 12:00:00 on a date.
In this example, the first 3 dates are consecutive cross weekend (weekend is holiday so count as leave), then another group of 3 dates cross weekend and month.
Now, what I am trying to do is find sequential dates (cross week and month) and put them into an array as follows:
[
1491408000000,
1491494400000,
1491753600000
],
[
1493222400000,
1493308800000,
1493568000000
]
I have tried the following code to get the sequential dates but this cannot cross week and month, how to modify the code to get above result? Any help would be much appreciated!
var timeValue = new Date(dateReview).getTime();
valueCon.push(timeValue);
var k = 0;
sortedValue[k] = [];
valueCon.sort( function ( a, b ){
return +a > +b ? 1 : +a == +b ? 0: -1;
})
.forEach( function( v , i ){
var a = v,b = valueCon[i+1]||0;
sortedValue[k].push( +a );
if ( (+b - +a) > 86400000) {
sortedValue[++k] = []
}
return 1;
});
sortedValue.sort( function ( a,b ){
return a.length > b.length ? -1: 1;
});
This requires help from a function to test if two dates are in the same week. The following goes over the set of time values provided in an array and puts the first value into an array within the array. For each subsequent value, it tests if it's in the same week as the first value in each array within the outer array.
If it's in the same week as the first value in any existing array, it's pushed into that array. Otherwise, it's put in a new array and pushed into the outer array.
There may be a neater way to implement the algorithm, but I'll leave that for others.
Due to time zone differences, they are adjusted to the host time zone based on the original time values representing noon in the source time zone.
// Given 2 dates, return true if they are in the same week (Mon to Sun).
// Otherwise, return false
function sameWeek(a, b){
var e = new Date(+a);
// Week starts at 00:00:00.000 on Monday on or before date
var s = new Date(e.setDate(e.getDate() - ((e.getDay()||7) -1)));
s.setHours(0,0,0,0);
// Week ends at 23:59:59.999 the following Sunday
e.setDate(e.getDate() + 6);
e.setHours(23,59,59,999);
// Test b and return value
return b >= s && b <= e;
}
// Given time value for UTC-0400, adjust to same date and time
// in local time zone and return a date
function adjust(n) {
var d = new Date(n);
d.setMinutes(d.getMinutes() - 240 + d.getTimezoneOffset());
return d;
}
var result = [1491408000000,1491494400000,1491753600000,1493222400000,1493308800000,1493568000000
].reduce(function(acc, n) {
var d = adjust(n);
var used;
if (acc.length != 0) {
used = acc.some(function(arr) {
if (sameWeek(adjust(arr[0]), d)) {
arr.push(n);
return true;
}
});
}
if (!used || acc.length == 0) {
acc.push([n]);
}
return acc;
},[]);
// Result array
console.log(result);
// Printed as date strings adjusted to same host local time
result.forEach(arr => {
arr.forEach(n => console.log(adjust(n).toString()))
console.log('\n');
});
Manipulation of timestamps is a pain. JavaScript has a built-in Date type, as you know, and I would suggest you use it. Date#getUTCDay returns the day of the week as an integer (for reference, 4 is Friday, or the day before a weekend), while Date#setUTCDate and Date#getUTCDate together allow you to adjust the date in day increments (and have it overflow/underflow to the next/previous month). Thus, to determine whether a timestamp b follows "sequentially" (excluding weekends) after a, you can use:
function sequential (a, b) {
a = new Date(a)
return a.setUTCDate(a.getUTCDate() + (a.getUTCDay() === 4 ? 3 : 1)) === b
}
Grouping is just an exercise after that; the code above contains all of the real logic behind this solution.
Example Snippet
var dates = [
1491408000000,
1491494400000,
1491753600000,
1493222400000,
1493308800000,
1493568000000
]
function sequential (a, b) {
a = new Date(a)
return a.setUTCDate(a.getUTCDate() + (a.getUTCDay() === 4 ? 3 : 1)) === b
}
function groupSequential(dates) {
if (dates.length < 2) return [dates.slice()]
dates.sort(function(a, b) { return a - b })
var result = [], group
for (var i = 0; i < dates.length; i++) {
sequential(dates[i - 1], dates[i]) || result.push(group = [])
group.push(dates[i])
}
return result
}
console.log(groupSequential(dates))
i have an array in javascript that looks like this
Array[9]
0: "01/06/2016"
1: "02/06/2016"
2: "23/05/2016"
3: "24/05/2016"
4: "25/05/2016"
5: "26/05/2016"
6: "27/05/2016"
7: "28/05/2016"
8: "31/05/2016"
length: 9__proto__: Array[0]
i want to order them so the oldest date is first and the most recent is last.
i have tried
days.sort(function(a,b) {
return new Date(a).getTime() - new Date(b).getTime()
});
but i guess because of the format of the date? this doesn't work.
what else could i try?
expected output
Array[9]
0: "23/05/2016"
1: "24/05/2016"
2: "25/05/2016"
3: "26/05/2016"
4: "27/05/2016"
5: "28/05/2016"
6: "31/05/2016"
7: "01/06/2016"
8: "02/06/2016"
length: 9__proto__: Array[0]
You can slit the string to year, month, date and use that to create the date for comparing.
new Date("01/06/2016") is wont be parsed as you think. The result actually is Jan 06 2016.
days = ["01/06/2016", "02/06/2016", "23/05/2016", "24/05/2016", "25/05/2016", "26/05/2016", "27/05/2016", "28/05/2016", "31/05/2016"];
days.sort(function(a, b) {
aArr = a.split('/');
bArr = b.split('/');
return new Date(aArr[2], Number(aArr[1])-1, aArr[0]).getTime() - new Date(bArr[2], Number(bArr[1])-1, bArr[0]).getTime()
});
console.log(days);
It's because the format Date uses in your case is MM/DD/YYYY
new Date("01/06/2016");
> Wed Jan 06 2016 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
See also http://www.w3schools.com/js/js_date_formats.asp
But from your list i assume your dates are in DD/MM/YYYY format.
3 possible solutions:
use a different format in your list
You could split your string up and create the Date via new Date(year, month, day); in your sort function.
use an advanced date/time library, i recommend moment.js http://momentjs.com/
var array= [ "01/06/2016" ,
"02/06/2016" ,
"23/05/2016" ,
"24/05/2016" ,
"25/05/2016" ,
"26/05/2016" ,
"27/05/2016" ,
"28/05/2016" ,
"31/05/2016" ];
array.sort(function (a, b) {
var dateParts1 = a.split("/");
var dateParts2 = b.split("/");
var dateA=dateParts1[2]*360+ dateParts1[1]*30+ dateParts1[0];
var dateB=dateParts2[2]*360+ dateParts2[1]*30+ dateParts2[0];
if (dateA > dateB) {
return 1;
}
if (dateA < dateB) {
return -1;
}
return 0;
});
please separate the parsing and the sorting-operations and cache the intermediate-values.
days = ["01/06/2016", "02/06/2016", "23/05/2016", "24/05/2016", "25/05/2016", "26/05/2016", "27/05/2016", "28/05/2016", "31/05/2016"];
days.map(v => { //parsing
var a = v.split("/");
return {
value: v,
ts: +new Date(+a[2], a[1]-1, +a[0])
}
})
.sort((a,b) => a.ts - b.ts) //sorting
.map(o => o.value); //returning the associated (input-)values
For n items in the input-array, the sorting-function may be called up to n * (n-1) times, depending on the implemented sorting-algorithm.
That's in this case, up to 144 times parsing such a string, in the worst case.
In the very best case (array already sorted) the other implementations here have to parse at least 16 times for this 9 items. (8 comparisons * 2 strings to parse)
This may not sound like much (yet), but these numbers increase exponentially.
Please try this:
var array = ["01/06/2016", "02/06/2016", "23/05/2016", "24/05/2016", "25/05/2016", "26/05/2016", "27/05/2016", "28/05/2016", "31/05/2016"];
function dateString2Date(dateString) {
var dt = dateString.split(/\//);
return new Date(dt[2]+"-"+dt[1]+"-"+dt[0]);
}
for(var i =0 ; i<=array.length-2;i++){
for(var j=i+1; j<=array.length-1;j++){
if(dateString2Date((array[i])).getTime()/1000> dateString2Date((array[j])).getTime()/1000){
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
console.log(array)