2013-02-26 34 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