2013-02-26 42 views
1

我有一個叫做dateTime []的二維數組。 dateTime [count] [0]包含未來的日期時間和dateTime [count] [1]包含4位數值,如1234或其他。 我正在嘗試按升序對dateTime [count] [0]進行排序。 (I,E,排序二維數組的colunm 0根據從現在最接近的日期時間)如何在二維數組中排序一個列

假設我的javascript二維數組是這樣的:

dateTime[0][0] = 2/26/2013 11:41AM; dateTime[0][1] = 1234; 
dateTime[1][0] = 2/26/2013 10:41PM; dateTime[1][1] = 4567; 
dateTime[2][0] = 2/26/2013 8:41AM; dateTime[2][1] = 7891; 
dateTime[3][0] = 3/26/2013 8:41AM; dateTime[3][1] = 2345; 

我只是寫這樣其實我這是怎麼插入價值dateTime[count][0] ; = new Date(x*1000);其中x是UNIX時間()

我想怎麼數組排序後看:

dateTime[0][0] = 2/26/2013 8:41AM; dateTime[0][1] = 7891; 
dateTime[1][0] = 2/26/2013 11:41AM; dateTime[1][0] = 1234; 
dateTime[2][0] = 2/26/2013 10:41PM; dateTime[2][1] = 4567; 
dateTime[3][0] = 3/26/2013 8:41AM; dateTime[3][1] = 2345; 

請讓我知道如何與解決這個少代碼。

謝謝。 :)

這我做了什麼到現在(我沒有排序的數組,這裏還日期時間被稱爲定時器)

function checkConfirm() { 
     var temp = timers[0][0]; 
     var timeDiv = timers[0][1]; 
     for (var i=0;i<timers.length;i++) { 
      if (timers[i][0] <= temp) { temp = timers[i][0]; timeDiv = timers[i][1]; } 
     } 
     if (timers.length > 0){ candidate(temp,timeDiv); } 

    } 

    function candidate(x,y) { 
     setInterval(function() { 
      var theDate = new Date(x*1000); 
      var now = new Date(); 
      if ((now.getFullYear() === theDate.getFullYear()) && (now.getMonth() === theDate.getMonth())) { 
       if ((now.getDate() === theDate.getDate()) && (now.getHours() === theDate.getHours())) { 
        if (now.getMinutes() === theDate.getMinutes() && (now.getSeconds() === theDate.getSeconds())) { alert("its time"); } 
       } 
      } 
     }, 10); 
    } 

末,我想每次都提醒用戶噹噹前時間與數組中的時間相匹配。這是我試圖解決問題的方法,但這是完全錯誤的方法。

+0

我已經更新了問題 – user1846348 2013-02-26 20:12:58

回答

2

使用.sort()函數,並比較日期。

// dateTime is the array we want to sort 
dateTime.sort(function(a,b){ 
    // each value in this array is an array 
    // the 0th position has what we want to sort on 

    // Date objects are represented as a timestamp when converted to numbers 
    return a[0] - b[0]; 
}); 

DEMO:http://jsfiddle.net/Ff3pd/

+0

謝謝你這麼多。 – user1846348 2013-02-26 20:14:14

+0

不客氣:-) – 2013-02-26 20:14:45