合并并给出浓缩时间javascript

时间:2017-03-18 09:07:18

标签: javascript

我试图解决面试蛋糕问题。

  

基本上,我需要编写一个函数mergeRanges(),它需要一个   会议时间范围的数组,并返回一个浓缩范围数组。

示例:

D QSEECOMAPI: QSEECom_get_handle sb_length = 0xa000
D QSEECOMAPI: App is already loaded QSEE and app id = 4
D QSEECOMAPI: QSEECom_dealloc_memory 
D QSEECOMAPI: QSEECom_shutdown_app, app_id = 4
D QSEECOMAPI: QSEECom_get_handle sb_length = 0xa000
D QSEECOMAPI: App is already loaded QSEE and app id = 4
D QSEECOMAPI: QSEECom_dealloc_memory 
D QSEECOMAPI: QSEECom_shutdown_app, app_id = 4
E QSEECOMAPI: Error::ioctl call to update the encryption key for usage 4 failed with ret = -1, errno = 22

预期产出:

[
    {startTime: 0,  endTime: 1},
    {startTime: 3,  endTime: 5},
    {startTime: 4,  endTime: 8},
    {startTime: 10, endTime: 12},
    {startTime: 9,  endTime: 10},
]

我的尝试:

[
    {startTime: 0, endTime: 1},
    {startTime: 3, endTime: 8},
    {startTime: 9, endTime: 12},
]

但似乎我没有定义startTime。有人可以帮助我解开这个谜团吗?

谢谢

1 个答案:

答案 0 :(得分:1)

基本上你有一个对象作为累加器,然后累加器是空的,任何访问累加器的尝试都得到undefined

您可以按startend对数组进行排序,并对已排序的数组进行迭代,并检查范围是否重叠。



var data = [{ startTime: 0,  endTime: 1 }, { startTime: 3,  endTime: 5 }, { startTime: 4,  endTime: 8 }, { startTime: 10, endTime: 12 }, { startTime: 9,  endTime: 10 }],
    result = data
        .sort(function (a, b) { return a.startTime - b.startTime || a.endTime - b.endTime; })
        .reduce(function (r, a) {
            var last = r[r.length - 1] || {};
            if (a.startTime <= last.endTime) {
                if (last.endTime < a.endTime) {
                    last.endTime = a.endTime;
                }
                return r;
            }
            return r.concat(a);
        }, []);

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;