如何合并具有相似开放时间的日期

时间:2015-05-20 22:38:11

标签: javascript

我正在尝试编写一个javascript函数来合并与商店类似开放时间的日子。例如,如果我们有:

"小时":[ "周五上午11:00 - 下午3:00,下午5:00 - 晚上10:00", "周一上午11:00 - 下午3:00,下午5:00 - 晚上9:30", "星期六中午12:00 - 晚上10:00", "周日中午12:00 - 下午9:30", "周四上午11:00 - 下午3:00,下午5:00 - 晚上9:30", "星期二上午11:00 - 下午3:00,下午5:00 - 晚上9:30", "周三上午11:00 - 下午3:00,下午5:00 - 晚上9:30" ],

我希望代码将其简化为:

"小时":[ " Mo-Sa 11:00-14:30", " Mo-Th 17:00-21:30", " Fr-Sa 17:00-22:00" ],

有没有一种方法可以在没有长if/elsecase个陈述的情况下完成此操作?

2 个答案:

答案 0 :(得分:2)

功能齐全,可以节省很多麻烦。

假设这是您的数据:

var data = [
    {day: "Mon", open: 900, close: 1700},
    {day: "Tue", open: 900, close: 1700},
    {day: "Wed", open: 700, close: 1700},
    {day: "Thu", open: 900, close: 1700},
    {day: "Fri", open: 900, close: 1700},
    {day: "Sat", open: 900, close: 1900},
    {day: "Sun", open: 900, close: 1900},
];

您可以简单地将数组reduce转换为6行代码中的合并数组:

var merged = data.reduce(function(preVal, curVal) {
    var last = preVal[preVal.length - 1];
    if (last && last.open == curVal.open && last.close == curVal.close) {
        last.endDay = curVal.day;
    } else {
        preVal.push(curVal);
    }
    return preVal;
}, []);

以防调试:

for (var i in merged) {
    var m = merged[i];
    var endDay = m.endDay ? " to " + m.endDay : "";
    console.log(m.day + endDay + " " + m.open + "-" + m.close);
}

BONUS 现在,如果您必须将merged转换为其他格式(例如,您需要在屏幕上打印的内容),您可以再次使用{{1}合并成你想要的任何格式:

map

答案 1 :(得分:1)

我建议将您的数据分解为比您目前在评论中指定的更为结构化的格式,例如:

var data = [
  { day: "Mon", hours: "11:00 AM to 10:30 PM" },
  { day: "Thu", hours: "11:00 AM to 10:30 PM" },
  { day: "Tue", hours: "11:00 AM to 10:30 PM" },
  { day: "Wed", hours: "11:00 AM to 10:32 PM" },
  { day: "Fri", hours: "11:00 AM to 10:00 PM" },
  { day: "Sat", hours: "11:00 AM to 10:00 PM" },
  { day: "Sun", hours: "11:00 AM to 10:30 PM" }
];

现在你可以按照相同的小时迭代这些日子和小组:

function collapseHours(data) {
  var collapsed = [];
  var idx = -1;
  for(var i=0; i<data.length; i++) {
    var day = data[i];
    if(idx == -1 || collapsed[idx].hours != day.hours) {
      collapsed.push({days:[day.day],hours:day.hours});
      idx++;
    } else {
      collapsed[idx].days.push(day.day);
    }
  }
  return collapsed;
}

collapseHours(data)会产生以下内容:

[
  {"days":["Mon","Thu","Tue"],"hours":"11:00 AM to 10:30 PM"},
  {"days":["Wed"],"hours":"11:00 AM to 10:32 PM"},
  {"days":["Fri","Sat"],"hours":"11:00 AM to 10:00 PM"},
  {"days":["Sun"],"hours":"11:00 AM to 10:30 PM"}
];

现在你可以像这样打印你的小时:

function prettyPrintHours(collapsed) {
   var lines = [];
   for(var i=0; i<collapsed.length; i++) {
     var line = collapsed[i];
     var days = line.days;
     if(days.length == 1) {
       lines.push(days[0]+" "+line.hours);
     } else {
       lines.push(days[0]+"-"+days[days.length-1]+" "+line.hours);
     }
   }
   return lines;
}

将产生:

[
 "Mon-Tue 11:00 AM to 10:30 PM",
 "Wed 11:00 AM to 10:32 PM",
 "Fri-Sat 11:00 AM to 10:00 PM",
 "Sun 11:00 AM to 10:30 PM"
]

鉴于这两个功能,根据您的确切需要自定义数据格式和输出格式应该相对简单。