Varun Sreedharan Varun Sreedharan - 1 month ago 5
jQuery Question

Grouping first and last value in array (Consecutive values are group with first and last element)

I have one object array with time intervals , Number 0 indicates sunday . In my time scheduling page selecting different time ranges in a particular day . I want to group the time values . My initial array is given below

time schedule selection looks like

enter image description here

Each cell has

data-day
and
data-time
attribute and selected cell with
data-selected
attribute

i am iterate through the selected time and got the result like

var selectedIntervals = {};

$('td[data-selected]').each(function() {
var a = $(this).attr('data-day');
var b = $(this).attr('data-time');

if(!selectedIntervals[a]) {
selectedIntervals[a]=[];
}
selectedIntervals[a].push(b);
});


enter image description here

I want the output like

{
0: [["00:00", "05:00"],["08:00", "11:00"]]

}


Please help .

Answer

Try this:

arr = ["00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "08:00", "09:00", "10:00", "11:00"];
output = [];
start = arr[0];
for(i=1; i<arr.length; i++) {
    if(i == arr.length-1) {
        output.push([start, arr[i]]);   
        break;
    }
    if(parseInt(arr[i]) - parseInt(arr[i-1]) > 1) {
        output.push([start, arr[i-1]]);
        start = arr[i];
    }
}