Javascript数组排序并制定与天数范围相同的时间表

标签 javascript sorting date range days

我收到了 CSV 格式的办公日程表,其中包含具有相同日程安排的日期的破折号范围。

例如,今天是星期四:

Mon 3:00am - 9:00pm, Tue - Thu 5:30am - 9:30pm, Fri 7:15am - 10:00pm, Sat 8:00am - 3:00pm, Sun Closed

我需要删除周日关闭时间表并首先显示周四,例如,如果今天是周四

我的预期输出是这样的:

Tue - Thu 5:30am - 9:30pm, Fri 7:15am - 10:00pm, Sat 8:00am - 3:00pm, Mon 3:00am - 9:00pm

如果今天是星期四(当天),一些示例和预期结果:

“周一 4:00am - 9:00pm,周二 6:00am - 9:30pm,周三 - 周五 5:30am - 9:30pm,周六 8:00am - 3:00pm,周日休息” 预期结果:“周二 6:00am - 9:30pm,周三 - 周五 5:30am - 9:30pm,周六 8:00am - 3:00pm,周一 4:00am - 9:00pm”

“周三 5:30am - 9:30pm,周四 6:30am - 4:00pm,周五至周二 8:00am - 3:00pm,周日休息” 预期结果:'周四上午 6:30 - 下午 4:00,周五至周二上午 8:00 - 下午 3:00,“周三上午 5:30 - 下午 9:30”

“周一至周二上午 5:30 - 下午 9:30,周三上午 6:30 - 下午 4:00,周四至周六上午 8:00 - 下午 3:00,周日休息” 预期结果:“周四至周六上午 8:00 - 下午 3:00,周一至周二上午 5:30 - 晚上 9:30,周三上午 6:30 - 下午 4:00”

我当前的代码部分工作:

function sortDays(days) {
    var dayOfWeek = new Date().getDay();
    var list = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    var sortedList = list.slice(dayOfWeek).concat(list.slice(0, dayOfWeek));
    return days.sort(function(a,b) { return sortedList.indexOf(a) > sortedList.indexOf(b); });
}

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}

function getDaysRange(first, last) {
    // var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    var week = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

    // Find first day
    var firstIndex = week.indexOf(first);
    // Shift array so that first day is index 0
    week = week.concat(week.splice(0, firstIndex));
    // Find last day
    var lastIndex = week.indexOf(last);

    // Cut from first day to last day and convert to CSV string
    // return week.slice(0, lastIndex + 1).toString();
    return week.slice(0, lastIndex + 1);
}



function reorderSchedule(schedule) {

    var detailedSchedule = [];
    var daysInWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    var scheduleExploded = schedule.split(',');
    var schedulehtms = '';

    console.log('===============================>>>>>>>>>>>>>>>>>>>');
    for (var i = 0, len = scheduleExploded.length; i < len; i++) {
        schedulehItem = scheduleExploded[i].trim();
        console.log(schedulehItem + ' = LOOP NUMBER ' + i + ' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');

        var count = (schedulehItem.match(/-/g) || []).length;
        console.log(count + " piece(s) of - found inside " + schedulehItem);

        if (count >= 2) {
            console.log(schedulehItem + ' is a range! ===============');

            // break down the days range
            var search = schedulehItem.search(/\d/);

            var scheduleOfRange = schedulehItem.substring(search, schedulehItem.length);
            console.log(scheduleOfRange);
            var daysRange = schedulehItem.substring(0, search - 1);
            console.log(daysRange);

            var arr = daysRange.split('-');
            var first = arr[0].trim();
            var second = arr[1].trim();

            var daysRange = getDaysRange(first, second);
            daysRange = removeA(daysRange, 'Sun');
            console.log(daysRange);
            console.log('>>>>>>>');

            for (x = 0; x < daysRange.length; x++) { 
                detailedSchedule.push(daysRange[x] + ' ' + scheduleOfRange);
            }

        } else {
            // insert the schedule in the final array
            detailedSchedule.push(schedulehItem);
        }

    }
    console.log('===============================>>>>>>>>>>>>>>>>>>>');
    console.log('=============');
    console.log(detailedSchedule);
    console.log('=============');

    var origDaysOnlyOrder = [];
    var daysWithScheduleOrder = [];
    var sortedDays = sortDays(daysInWeek);

    for (i = 0; i < detailedSchedule.length; i++) {        

        var myNewStr = detailedSchedule[i].substr(0, 3);
        // origDaysOnlyOrder.push(myNewStr);
        daysWithScheduleOrder[myNewStr] = detailedSchedule[i];
    }

    console.log('vvvvvvvvvvvvvvvvvvvvvvvvvvvv');
    console.log(daysWithScheduleOrder);
    console.log(sortedDays);

    var finalArray = [];
    for (i = 0; i < sortedDays.length; i++) {
        // don't insert undefined values
        if (typeof(daysWithScheduleOrder[sortedDays[i]]) != 'undefined') {
            // finalArray.push(daysWithScheduleOrder[sortedDays[i]]);
            finalArray[sortedDays[i]] = daysWithScheduleOrder[sortedDays[i]].substr(3).trim();
        }
    }

    // remove
    console.log(finalArray);
    console.log('######################>>>');

    // now in correct order then bring back the dash in the original range, check for same schedules then create the range
    // find first

    var scheduleObj = {};
    for (var key in finalArray) {
        var value = finalArray[key];
        // console.log(key, value);
        scheduleObj[key] = value;
    }
    console.log(scheduleObj);


    var hash = Object.create(null);
    var result = Object.create(null);

    Object.keys(scheduleObj).forEach(k => {
        var grp = scheduleObj[k];

        (grp in hash) ? hash[grp].push(k) : (hash[grp] = [k]);
    });

    for (key in hash) {
        if (hash[key].length > 1) {
            result[key] = hash[key].toString();
        }
    }

    console.log(hash);
    console.log('hash sa taas');


    var finalScheduleArray = [];
    // loop hash
    Object.keys(hash).forEach(function(key) {
        // console.log(key, result[key]);
        console.log(key, hash[key]);
        var my_key = key;
        var my_value = hash[key];


        if (my_value.length == 1) {
            finalScheduleArray[my_value] = my_key;
        } else {

            var rangeArray = [];
            for (i = 0; i < my_value.length; i++) {
                console.log(my_value[i]);
                rangeArray.push(my_value[i]);

            }
            console.log(rangeArray);

            var firstItem = rangeArray[0];
            var lastItem = rangeArray[rangeArray.length-1];
            finalScheduleArray[firstItem + ' - ' + lastItem] = my_key;
        }

    });

    console.log(finalScheduleArray);
    console.log('finalScheduleArray ----------');
    return 'zzz';
}

$(function() {
    // var schedule = 'Mon 4:00am - 9:00pm, Tue 6:00am - 9:30pm, Wed - Fri 5:30am - 9:30pm, Sat 8:00am - 3:00pm, Sun Closed'; // MALI Wed - Fri
    // var schedule = 'Mon 4:30am - 9:30pm, Tue 5:30am - 9:30pm, Wed 5:00am - 9:30pm, Thu - Sat 8:00am - 3:00pm, Sun Closed'; // tama Thu - Sat
    var schedule = 'Mon 3:00am - 9:00pm, Tue - Thu 5:30am - 9:30pm, Fri 7:15am - 10:00pm, Sat 8:00am - 3:00pm, Sun Closed'; // MALI Tue - Thu
    console.log(reorderSchedule(schedule));
});

最佳答案

以下内容可能会起作用,它不会删除“Sun”,不确定您是否只是想删除那一天还是因为它恰好关闭。

const week = [
  'Sun',
  'Mon',
  'Tue',
  'Wed',
  'Thu',
  'Fri',
  'Sat',
];
const withDayPair = (item) => {
  //add [dayOneIndex, dayTwoIndex] to value
  const parts = item
    .split('-')
    .map((s) => s.trim())
    .map((s) => s.substr(0, 3));
  if (parts.length > 2) {
    //this value has day range (for example Mon - Wed)
    return [
      parts.slice(0, 2).map((p) => week.indexOf(p)),
      item,
    ];
  }
  return [[week.indexOf(parts[0]), -1], item]; //only one day, set second day to -1
};
const assignValue = (current) => ([[a, b], item]) => {
  //assign a value for sorting. If both values are smaller than current (earlier in the week)
  //  then add 10 to the index of the value in the array
  const val = a < current && b < current ? a + 10 : a;
  return [val, item];
};
const sortWith = (str, day) =>
  str
    .split(',')
    .map((s) => s.trim())
    .filter((s) => !s.startsWith('Sun'))//remove sunday
    //having a string representing days of week is not the best way to represent
    //  the data types used in your application
    .map(withDayPair)
    //now the values will be [[1,3],'Mon - Wed ....']
    .map(assignValue(week.indexOf(day))) //the [1,3] part is replaced with one number
    .sort(([a], [b]) => a - b) //sorting on that number
    .map(([_, item]) => item); //remove the number
const testVal =
  'Mon - Tue 5:30am - 9:30pm, Wed 6:30am - 4:00pm, Thu - Sat 8:00am - 3:00pm, Sun Closed';
console.log(
  //test for every day in the week
  ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
    .map(
      (day) =>
        `Day:${day} == ${sortWith(testVal, day).join(',')}`,
    )
    .join('\n'),
);

关于Javascript数组排序并制定与天数范围相同的时间表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52426210/

相关文章:

R:数据表。如何使用 fwrite 正确保存日期?

ruby-on-rails - 在 Rails 3.1 中更改 created_at 的格式?

javascript - 异步请求后如何在路由中重定向?

javascript - ES6 从现有实例实例化派生类

javascript - 使 Javascript future 日期调整为周末

algorithm - 外部分类

php - 使用 Php 在 Mysql 中输入日期的问题

javascript - jqGrid - 从 JSON 加载值

java - 使用 Collections.sort() 时出错

java - 如何在字段上使用 RuleBasedCollat​​or 对 Java 对象列表进行排序?