Arya220 Arya220 - 5 months ago 16
JSON Question

Finding minimum and maximum date in an complex json array

I have a json array like this.

var data=[
{
Title:"Dummy1",
Events:[{
eventName:"StartDate"
Date:"Jan-2014"
},
{
eventName:"EndDate"
Date:"Feb-2015"
}]
},
{
Title:"Dummy2",
Events:[{
eventName:"StartDate"
Date:"Jan-2013"
},
{
eventName:"EndDate"
Date:"Feb-2015"
}]
},
{
Title:"Dummy3",
Events:[{
eventName:"StartDate"
Date:"Feb-2014"
},
{
eventName:"EndDate"
Date:"Mar-2015"
}]
}];


Please notice that dates are not date objects as such. they are strings.

I need to find the minimum of StartDate and maximum of EndDate
So the result should be

MinStartDate:Jan-2013
MaxEndDate:Mar-2015


I would prefer to use angular if not javascript or jquery is also fine.

thanks in advance.

Answer

There is my solution, this is a bit long, but very easy to understand and edit for any update. I'm sure we can solve it with 4-5 lines, but whatever, it works.

First, define a month array :

var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

Like every time you need to search min/max in an array, you need to initialize min and max with the first value :

var max_end_date = data[0].Events[1].Date;
var min_start_date = data[0].Events[0].Date;

And then, split every date for compare year / month for start en end, and you have a result like this :

$.each(data, function(k, v) {
    var month_min_start_date = min_start_date.split("-")[0];
    var year_min_start_date = min_start_date.split("-")[1];

    var current_start_date = v.Events[0].Date;
    var month_current_start_date = current_start_date.split("-")[0];
    var year_current_start_date = current_start_date.split("-")[1];

    if (year_current_start_date < year_min_start_date 
        || year_current_start_date == year_min_start_date && month.indexOf(month_current_start_date) < month.indexOf(month_min_start_date)) {
            min_start_date = current_start_date;
        }

    var month_max_end_date = max_end_date.split("-")[0];
    var year_max_end_date = max_end_date.split("-")[1];

    var current_end_date = v.Events[1].Date;
    var month_current_end_date = current_end_date.split("-")[0];
    var year_current_end_date = current_end_date.split("-")[1];

    if (year_current_end_date > year_max_end_date 
        || year_current_end_date == year_max_end_date && month.indexOf(month_current_end_date) > month.indexOf(month_max_end_date)) {
            max_end_date = current_end_date;
        }

})

You can try it on JSFiddle

Comments