user1891834
user1891834

Reputation: 13

Sorting multidimensional array jquery/javascript

var klas4 = [];

klas4[2] = [];
klas4[2]["hour"] = 1;
klas4[2]["teacher"] = "JAG";
klas4[2]["group"] = "V4A";
klas4[2]["subject"] = "IN";
klas4[2]["classroom"] = "B111";

klas4[0] = [];
klas4[0]["hour"] = 6;
klas4[0]["teacher"] = "JAG";
klas4[0]["group"] = "V4B";
klas4[0]["subject"] = "IN";
klas4[0]["classroom"] = "B111";

klas4[1] = [];
klas4[1]["hour"] = 4;
klas4[1]["teacher"] = "NAG";
klas4[1]["group"] = "V4A";
klas4[1]["subject"] = "NA";
klas4[1]["classroom"] = "B309";

This multidimensional array needs to be sorted by hour, ascending. The problem is, I don't know how to sort an multidimensional array. The first dimension (0, 1 and 2), needs to be changed, according to the hour, but all other details from dimension 2 (teacher, group etc.) also need to change from index, because otherwise the data is mixed. You don't know how many indexes there are. In this example, the correct sequence should be: klas4[2][...], klas4[1][...], klas[0][...]

In PHP there's a certain function multisort, but I couldn't find this in jQuery or JavaScript.

Upvotes: 1

Views: 3941

Answers (1)

tomdemuyt
tomdemuyt

Reputation: 4592

klas4.sort( function(a,b){ return a.hour - b.hour } );

should do it.

It helps to think of klas4 not as a multi-array but as 1 array of objects. Then you sort the objects in that array with a sort function.

The sort function takes 2 objects and you must return which one comes first.

You should read on sort() for Array, google that.

Also, as others have commented; the entries for klas4 are really objects, you should use

klas4[2] = {};

or even better

klas4[2] = { hour:1 , teacher:"JAG" , group:"V4A" , subject: "IN" };

Finally, I assume you are a native Dutch or German speaker, as I am. I would strongly suggest to name all your variables in English, class4, not klas4. It is the right, professional thing to do.

Upvotes: 4

Related Questions