user1846348
user1846348

Reputation: 241

How to sort just a single column in 2d array

I have a 2d array called dateTime[]. dateTime[count][0] contains future datetime and dateTime[count][1] contains a 4 digit value like 1234 or something. I am trying to sort the column 0 that is dateTime[count][0] in ascending order. ( i,e, sorting the colunm 0 of the 2d array according to closest datetime from now)

Suppose my javascript 2d array is like:

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;

I just wrote like this actually this is how I inserted value to dateTime[count][0] ; = new Date(x*1000); where x is unix time()

How I want the array to look after sorting:

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;

please let me know how to solve this with less code.

Thanks. :)

This what I have done till now (I haven't sorted the array, also here dateTime is called timers)

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);
    }

AT the end, I wanted to alert the user every time when the current time matches the time in the array. This is how I tried to solve the problem but this is completely wrong approach.

Upvotes: 1

Views: 822

Answers (1)

gen_Eric
gen_Eric

Reputation: 227270

Use the .sort() function, and compare the dates.

// 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/

Upvotes: 2

Related Questions