In the last post I explained the solution to sort a propertyset. In this post I am going to explain the solution to sort a 2D array in Siebel. A 2D array is very similar to a propertyset. Simple property sets can easily be represented by way of 2D array.
Let’s take the same example as in the last post and assume that the information is now available in form of a 2D array
|
Row Id |
Date |
Status |
Comments |
|
1 |
08/08/2011 |
Open |
Test |
|
2 |
07/07/2011 |
In Process |
Test2 |
|
3 |
09/09/2011 |
Closed |
Test3 |
Before moving on the solution of sorting a 2D array. I would just like to post a sample code of creating a 2D array (might be useful for beginners).
Creating a 2D Array:
var testAr:Array = new Array();
var row =0; var i=0; var j=1; var l=888;
for(i=0;i<30;i++)
{
//just to randomize the date
if(j>9)j=1;
if(j>15)j=2;
if(j>20)j=1;
//add the date to array
testAr[row] = new Array(); //allocate memory
testAr[row][0] = “08/” + j + “/2011″; //assign values
testAr[row][1] = “comment ” + i;
testAr[row][2] = l;
testAr[row][3] = “In Process”;
i++;j++;l++;
row++;
}
The sample code above will create a 2D array (testAr) with the information that we need to sort. A simple array can be easily sorted by using sort method of array object for example sampleAry.sort().
Solution: Sorting a 2D Array
2D array can be sorted using sort method of array but a function name has to be passed as an argument to the sort method. That function works on two implicit arguments “a” and “b” to achieve sorting.
Here is the sample code that can sort the testAr array defined using the sample code above.
testAr.sort(sortAry); //pass function name without round ()
function sortAry(a,b)
{
return(Date.parse(a[0]) == Date.parse(b[0]) ? 0 : (Date.parse(a[0]) < Date.parse(b[0]) ? 1 : -1) )
}
Explanation:
‘a’ and ‘b’ are two special variables that represent the 1st & 2nd, 2nd & 3rd, 3rd & 4th, etc., elements to compare (It’s good practice NEVER to use ‘a’ and ‘b’ as variables in your script). ‘a’ and ‘b’ are set to what you want to use for comparison.
The function needs to return -1, 0, or 1 to give you the sort order.
To Sort Ascending
a < b returns -1
a = b returns 0
a > b returns 1
To Sort Descending
a < b returns 1
a = b returns 0
a > b returns -1
So, the code below sorts it in descending order
Date.parse(a[0]) == Date.parse(b[0]) ? 0 : (Date.parse(a[0]) < Date.parse(b[0]) ? 1 : –1) //if dates are equal then return 0 else if date a < date b then return 1 else return –1
Just change 1 to –1 and vice versa to achieve sorting in descending order
Date.parse(a[0]) == Date.parse(b[0]) ? 0 : (Date.parse(a[0]) < Date.parse(b[0]) ? -1 : 1) //if dates are equal then return 0 else if date a < date b then return -1 else return 1
I tried to generalize the code by passing mode and column index on which sorting needs to be done but was not successful. Do provide your comments or a better solution if you have.
