在JavaScript中从日期数组中获取日期范围字符串

时间:2018-10-25 21:24:34

标签: javascript arrays

我有很多天

[0,1,4,5,6]

这些天如何以类似的格式打印

“星期四,周六,周日”

var hours = {
  firstSet: { 
     days: [0,1,4,5,6]
  },
  secondSet: { 
     days: [1,4,6]
  }
};

var prevDay = null;
    var counter = 0;
    function loadHours() {
        $.each(hours,function(id,val){
            prevDay = null;
            counter = 0;
            var dayString = "";
            $.each(val.days, function(day){
                counter += 1;

                if (counter == 1) {
                    dayString += checkDayString(prevDay, day);
                } else if (counter == val.days.length) {
                    dayString += "-"+getDayName(day);
                }
            });
        });
    }

    function checkDayString(prevDay, day) {
        if (prevDay == null) {
            prevDay = day;
            return getDayName(day);
        }
    }

    function getDayName(day) {
        switch(day) {
            case 0:
                return "Sun";
                break;
            case 1:
                return "Mon";
                break;
            case 2:
                return "Tue";
                break;
            case 3:
                return "Wed";
                break;
            case 4:
                return "Thu";
                break;
            case 5:
                return "Fri";
                break;
            case 6:
                return "Sat";
                break;
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用reduce对数组中出现的连续天进行分组,然后使用map使用数字组的第一个和最后一个索引将其转换为单词范围。

var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var ranges = [0, 1, 4, 5, 6];

var words = ranges
  .reduce((acc, curr) => {
    if (acc.length === 0) {
      acc.push([curr]);
      return acc;
    }
    let r = acc[acc.length - 1];
    if (curr - r[r.length - 1] === 1) r.push(curr);
    else acc.push([curr]);
    return acc;
  }, [])
  .map(range => range.length === 1 ?
    days[range[0]] :
    days[range[0]] + "-" + days[range[range.length - 1]])

console.log(words.join(', '));