0

Hello I have the following question:

I have a bidimensional array which look like this:

[[2, C, 22, 22, 8]
[2, C, 22, 22, 7]
[2, C, 22, 22, 10]
[1, R, 45, 45, 4]
[1, R, 45, 45, 3]
[1, R, 45, 45, 2]
[1, R, 45, 45, 1]
[1, R, 150, 100, 6]
[1, R, 150, 100, 5] 
[1, C, 22, 22, 9]]

And I want to order the data first for column 1, then for column 2, then for column 3, then for column 4, then for column 5; all in descending order. The following is the result that I want to obtain:

[[2, C, 22, 22, 10]
[2, C, 22, 22, 8]
[2, C, 22, 22, 7]
[1, R, 150, 100, 6]
[1, R, 150, 100, 5]
[1, R, 45, 45, 4]
[1, R, 45, 45, 3]
[1, R, 45, 45, 2]
[1, R, 45, 45, 1]
[1, C, 22, 22, 9]]

I use ExtendScript which is an extended version of Javascript for Adobe. How is this possible with Javascript? Any suggestions would be much appreciated. Thanks in advance

Andre Silva
  • 4,782
  • 9
  • 52
  • 65

1 Answers1

4

Had the numbers flipped. Updated with working example.

You can use Array.prototype.sort then loop through the options. (make sure to put quotes around your strings though!)

var x = [[2, "C", 22, 22, 8],
[2, "C", 22, 22, 7],
[2, "C", 22, 22, 10],
[1, "R", 45, 45, 4],
[1, "R", 45, 45, 3],
[1, "R", 45, 45, 2],
[1, "R", 45, 45, 1],
[1, "R", 150, 100, 6],
[1, "R", 150, 100, 5] ,
[1, "C", 22, 22, 9]];


x.sort(function(a,b){
    for(var i=0; i<a.length; i++) {
        if(a[i] > b[i]) {
            return -1;
        }
        if(a[i] < b[i]) {
            return 1;
        }

    }
    return 0;
})

Note that I'm assuming that all arrays are the same length and that a simple < and > is sufficient for comparison. If your needs differ it should be trivial to adapt to that.

Working example: http://jsfiddle.net/zSHw9/

Community
  • 1
  • 1
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
  • No, i just checked it. If you change [1, "C", 22, 22, 9] to [1, "Z", 22, 22, 9], it will still be placed at the end of the sorted array but it should be at index 3. – basilikum May 15 '13 at 16:46
  • @basilikum Good point. I got too clever trying to condense it. Switched it back to the original solution with < and > – Ben McCormick May 15 '13 at 16:53