I must be missing the proper term or else I’m sure I could find the answer by searching… in any case, here’s what I want to do.
Through javascript, I get four variables (A, B, C, and D) that I would like to sort, and still keep track of the variable name (since it’s encoded with meaning information).
Sample Data:
A = 2;
B = 1;
C = 4;
D = 3;
What I need to do now is sort them in value order (4,3,2,1) such that I can actually know the variable name ordering (C,D,A,B).
You can keep an array of value pair objects and then simply sort that array. Of course, the array’s sort method need to know how to interpret the object but that can be done by supplying a comparison function to the sort method.
First declare your array of objects:
Then write a comparison function:
Then simply sort and reverse:
To print out the sorted names simply iterate through the array: