7

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 Answers 3

26

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I know this is an old post but it's an awesome answer and it's helped me crack a problem with my own custom table sort plugin I'm making :)
How come javascript made it convoluted by making the user return 1, 0 or -1. Instead why not do it like python where its just arr.sort( (a,b) => a[0] < b[0). assuming arr is an array of arrays and you want to sort by the first element of the inner array.
6

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

2 Comments

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?
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
1

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

1 Comment

Works great in Chrome. 'this.sort' throws an error in Firefox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.