开发者

Sorting a multidimensional array in javascript

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 t开发者_运维百科he date arrays, is this possible?

data stucture:

events = [
 { date 1, date 2, string },
 { date 2, date 2, string },
 ]


Duplicate of 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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜