Combining Duplicate “Nested” Arrays Javascript (Using for weekly open and closed hours)

六月ゝ 毕业季﹏ 提交于 2019-12-11 14:58:09

问题


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:


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.



来源:https://stackoverflow.com/questions/22392490/combining-duplicate-nested-arrays-javascript-using-for-weekly-open-and-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!