2017-02-27 70 views
1

我解決這個問題:合併對象,並返回冷凝範圍對象

寫功能mergeRanges(),它滿足時間 範圍的陣列,並返回冷凝範圍(1 = 30分鐘的陣列)

Input: 
[ 
    {startTime: 0, endTime: 1}, // meeting from 10:00 – 10:30 am (1 = 30 minutes) 
    {startTime: 3, endTime: 5}, // meeting from 12:00 – 1:30 pm 
    {startTime: 4, endTime: 8}, 
    {startTime: 10, endTime: 12}, 
    {startTime: 9, endTime: 10}, 
] 

Expected Output: 

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

我的解決辦法是/如下:

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

function result(arr){ 
    var finalResult = {}; 

    var c = arr.sort(function(a,b){ //First Sort 
    return a.startTime - b.startTime; 
    }); 

    var d = c.reduce(function(a,b){ 

    //Logic 

    //check to see if start time lies between a[start] < b[startTime] < a[end] 

    // If the startTime lies between a[startTime] to b[endTime] -> Merge them. 

// if(a[startTime]< b[startTime] < b[endTime]){ //if start time lies between start and end. 
    // a[endTime] = b[endTime]; 
    // delete b; 
    // } 

    }); 

} 

result(arr); 

我無法理解如何使用reduce函數來交換邏輯。有人能夠啓發我嗎?

+0

什麼叫 「交換邏輯」 是什麼意思? –

回答

1

您可以使用reduce()和一個變量來存儲endTime。

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

 
var c = 0; 
 
var result = input.reduce(function(r, e, i) { 
 
    //Check if c < startTime of current object in loop or if its first 
 
    //element and if it is add it to r 
 
    if (c < e.startTime || i == 0) { 
 
    r.push(e) 
 
    } else { 
 
    //if not check if endTime of current object is > c 
 
    //(so you don't have problem at last object where endTime is smaller then some previous endTime) and change it 
 
    //in r of last element that you added 
 
    if (e.endTime > c) r[r.length - 1].endTime = e.endTime 
 
    } 
 
    //Always set c to current endTime 
 
    c = e.endTime 
 
    return r 
 
}, []) 
 

 
console.log(result)

+0

r,e和i是什麼? (我是一個索引嗎?)爲什麼你把「C」標記爲0?你能解釋一下你的邏輯嗎?我很困惑你的解決方案。 (對不起,這個減少函數是最新的..最近開始學習)@Nenad Vracar – TechnoCorner

+0

好'r'是累加器或者在這種情況下它的數組,'e'是循環中的當前對象,'i'是你需要的索引只是爲了檢查它的第一個元素是否可以添加到數組中。 –