views:

64

answers:

1

Hi my problem is somewhat special or maybe not. However the problem is that I parse range of dates in one array, where I need to find start date and end date where ever it may occur in ranges. I do not know did I explain this well but if you need more info, please let me know.

e.g. [2010-7-11,2010-7-12,2010-7-13, 2010-9-01, 2010-9-02,....]

Now

2010-7-11 start and 2010-7-13 end

2010-9-01 start 2010-9-02 end

So on for entire ranges within array

Thanks in advance

A: 

Here's something quick and dirty. It expects the dates array to already be sorted in ascending order.

var dates = ["2010-7-11", "2010-7-12", "2010-7-13", "2010-9-01", "2010-9-02"],
    startDates = [], endDates = [],
    lastDate = null, date = null;

for ( var i=0, l=dates.length; i<l; ++i ) {
    date = new Date(dates[i].replace(/-/g, "/"));

    //
    if ( !lastDate ) {
        startDates.push(lastDate = date);
    }
    // If the diffrence between the days is greater than the number
    // of milliseconds in a day, then it is not consecutive
    else if ( date - lastDate > 86400000 ) {
        lastDate = null;
        endDates.push(date);
    }
}
// Close the last range
endDates.push(date);

// Result is two symetical arrays
console.log(startDates, endDates);
Justin Johnson
This is not working for instance if we have more than 3 elements in array no matter dates are ordered or not the 4 element is also designated as start date, even though it is part of consecutive... but thanks anyway
Narayan