0

This one is baking my noodle big time!

I have some arrays inside an array that looks like this

var lidHours = {"192611":[
["07:00","21:30"],
["07:00","21:30"],
["07:00","21:30"],
["09:00","21:30"],
["09:00","00:00"],
["08:00","08:00"],
["",""]
]
}

And an array of the week days

var weekDays = new Array("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun");

So each array represents a day of the week. I'm outputting onto the page like this: Monday: 7:00 - 21:00 and so on...

But you can see that the first 3 days have the exact same hours, my goal is to have it display like this:

Mon-Wed: 7:00 - 9:00
Thu: 9:00 - 9:30
Fri: 9:00 - 12:00
Sat: 8:00 - 8:00
Sun: Closed

I can format the hours and know when they are closed and convert from military to standard, but I cant figure out how to combine the duplicate hours(Mon-Wed) and how can I preserve Mon and know that the last duplicate day was Wed??

Any help would be so greatly appreciated. Thanks!

1
  • Simply iterate over the array and compare the start and end times? If two consecutive entries have the same times you can group them. Commented Mar 13, 2014 at 22:53

1 Answer 1

0
var combined_hours = [];
var openHours = lidHours["192611"];
var prevHours;
for (var day = 0; day < openHours.length; day++) {
    var curHours = openHours[day];
    if (curHours[0] != prevHours[0] || curHours[1] != prevHours[1]) {
        combined_hours.push({ startDay: weekDays[day],
                              endDay: "", 
                              open: curHours[0], 
                              close: curHours[1] });
        prevHours = curHours;
    } else {
        combined_hours[combined_hours.length-1].endDay = '-' + weekdays[day];
    }
}

Now you can display combined_hours.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much for your response! I am going to try this right now.
if this worked, why haven't you accepted it? I'm trying to link to it as a duplicate in another question, but SO won't let me do that when the answer hasn't been upvoted or accepted.
My guess is you made a mistake involving variable scope. Hard to do any better without seeing the full code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.