views:

309

answers:

3

How would you sort a multidimensional array in JavaScript?

I have an array full of arrays that contain two dates and a string. I need the main array sorted by one of the date arrays, is this possible?

data stucture:

events = [
 { date 1, date 2, string },
 { date 2, date 2, string },
 ]
+3  A: 

The array structure seems a little vague from your description. You can use a custom sort function to compare elements and do the sort.

Assuming the structure is:

var data = [
    [date11, date12, string],
    [date21, date22, string],
    [date31, date32, string],
    ...
];

If you had objects instead of nested arrays, you wouldn't need to use number indexes. Here a[0] and b[0] are used to compare the first item in two nested arrays (assuming its the date you want to sort by). Also, assuming that a[0] and b[0] are already objects of Date - you may need to create the Date objects if they aren't already.

Update: Thanks to @maerics for pointing this out. The return value from the comparator needs to be [negative, 0, positive] corresponding to [a < b, a == b, a > b] values.

function sortByDate(a, b) {
    return a[0].getTime() - b[0].getTime();
}

data.sort(sortByDate);
Anurag
You probably mean `return a[0].getTime() - b[0].getTime()` since the comparator should return (neg, zero, pos) depending on if (a<b, a==b, a>b), right?
maerics
Yep, thanks for the correction :)
Anurag
No point in using getTime(). a - b will result in a.valueOf() and b.valueOf() being used behind the scenes, which returns the unix time
Sean Kinsey
A: 

This example is for sorting arrays by numbers (and dates) or strings.

Array.prototype.deepsort= function(){
    var i, order= arguments, L= order.length, tem;
    return this.sort(function(a, b){
        i= 0;
        while(i < L){
            tem= order[i++];
            var ao= a[tem] || 0, bo= b[tem] || 0;
            if(ao== bo) continue;
            return ao> bo? 1: -1;
        }
        return 0;
    });
}

var a= [ [ 'z', 1, 0 ], [ 'a', 0, 1 ],['m',-1,10] ,['a','1',-1]];

alert(a.deepsort(0,1,2)+'\n\n'+a.deepsort(2,0,1)) 

Sorts on the selected index (passed as an argument).

If the items at that index in each array match, sorts on the next index passed as an argument, if any.

Continue as long as the items match and there are more arguments.

You don't need to specify more than one index to sort by

a.deepsort(0);
a.deepsort(2);
kennebec
Works great in Chrome. 'this.sort' throws an error in Firefox.
Kyle
+1  A: 

Duplicate of http://stackoverflow.com/questions/2793847/sort-outer-array-based-on-values-in-inner-array-javascript here you will find several answers, like my own

var arr = [.....]
arr.sort((function(index){
    return function(a, b){
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
    };
})(2)); // 2 is the index

This sorts on index 2

Sean Kinsey