Sort 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 a main array sorted by one of the date arrays, is this possible?

data structure:

events = [ { date 1, date 2, string }, { date 2, date 2, string }, ] 
+6
javascript arrays multidimensional-array
source share
3 answers

Duplicate sort the external array based on the values ​​in the internal array, javascript here you will find several answers, for example, 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 

It sorts by index 2

+13
source share

The array structure seems a bit vague from your description. You can use a custom sort function to compare items and sort.

Assuming the structure:

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

If you had objects instead of nested arrays, you would not need to use numeric indices. Here a[0] and b[0] are used to compare the first element in two nested arrays (counting its date that you want to sort). In addition, assuming that [0] and b [0] are already Date objects, you may need to create Date objects if they were not already.

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

 function sortByDate(a, b) { return a[0].getTime() - b[0].getTime(); } data.sort(sortByDate); 
+3
source share

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

Sort by the selected index (passed as an argument).

If the elements in this index in each array match, sorts by the next index passed as an argument, if any.

Continue until the elements match and there are more arguments.

You do not need to specify more than one index to sort by

 a.deepsort(0); a.deepsort(2); 
+1
source share

All Articles