Thursday, October 29, 2009

Two dimensional Array (Table Array) Multiple column sorting using JavaScript

Here is a JavaScript implementation for multi-column ascending sort on a table array.

Below is the code for this.
var tempArray = new Array();
//main function
function do2DArraySort(arrayToBeSorted, sortColumnArray)
{
if (arrayToBeSorted == "undefined" || arrayToBeSorted == "null") return arrayToBeSorted;
if (arrayToBeSorted.length == 0) return arrayToBeSorted;
if (sortColumnArray.length == 0) return arrayToBeSorted;
tempArray = arrayToBeSorted; 
var totalLength = sortColumnArray.length; 
for(var m = 0; m < totalLength; m++)
{
if (m == 0)
{   
doBubbleSort(tempArray, tempArray.length, sortColumnArray[m]);         
}
else
{     
doMultipleSort(tempArray, sortColumnArray[m], sortColumnArray[m-1]);
}
} 
return tempArray;
}

//basic bubble sort implementation
function doBubbleSort(arrayName, length, element) 
{
for (var i = 0; i < (length-1); i++)
{
for (var j = i+1; j < length; j++)            
{
if (arrayName[j][element] < arrayName[i][element]) 
{
var dummy = arrayName[i];
arrayName[i] = arrayName[j];
arrayName[j] = dummy;
}
}
}  
}

//appends an array content to the original array
function addToArray(originalArray, addArray)
{
if (addArray.length != 0)
{
var curLength = 0;
curLength = originalArray.length;
var maxLength = 0;
maxLength = curLength + addArray.length;  
var itrerateArray = 0;
for (var r = curLength; r < maxLength; r++)
{   
originalArray[r] = addArray[itrerateArray];
itrerateArray++;
}
}
}

//check if a value exists in a single dimensional array
function checkIfExists(arrayToSearch, valueToSearch)
{
if (arrayToSearch == "undefined" || arrayToSearch == "null") return false;
if (arrayToSearch.length == 0) return false;
for (var k = 0; k < arrayToSearch.length; k++)
{
if (arrayToSearch[k] == valueToSearch)
return true;
}
return false;
}

//sorts an 2D array based on the distinct values of the previous column
function doMultipleSort(sortedArray, currentCol, prevCol)
{
var resultArray = new Array(); 
var newdistinctValuesArray = new Array();
//finding distinct previous column values 
for (var n = 0; n < sortedArray.length; n++)
{ 
if (checkIfExists(newdistinctValuesArray, sortedArray[n][prevCol]) == false)
newdistinctValuesArray.push(sortedArray[n][prevCol]);
}  
var recCursor = 0;
var newTempArray = new Array(); var toStoreArray = 0; 
//for each of the distinct values
for (var pp = 0; pp < newdistinctValuesArray.length; pp++)
{
toStoreArray = 0;
newTempArray = new Array();  
//find the rows with the same previous column value
for (var qq = recCursor; qq < sortedArray.length; qq++)
{
if (sortedArray[qq][prevCol] != newdistinctValuesArray[pp]) break;
newTempArray[toStoreArray] = sortedArray[qq];
toStoreArray++; recCursor++;
}
//sort the row based on the current column   
doBubbleSort(newTempArray, newTempArray.length, currentCol);
//append it to the result array
addToArray(resultArray, newTempArray);
}
tempArray = resultArray;
}
The above code can be stored as TableArrayMultipleSort.js for our example usage shown below:
<html>
<head>
<title>Invoking Multiple Array Sort</title>
<script language="javascript" src="TableArrayMultipleSort.js" type="text/javascript"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function createSampleArray()
{ 
var myArr = new Array( 
new Array("Ashley","13","Male","Texas"),
new Array("Smith", "32", "Male","Colorado"),
new Array("Jane", "21", "Female","South Carolina"),
new Array("Anna", "12", "Female","Maryland"),
new Array("Ashley","13","Male","Delaware"),
new Array("Ashley","46","Male","Newyork")
); 
return myArr;
}
function showDataByRow(arrayToBeShown)
{
for(var a=0;a<arrayToBeShown.length;a++)
{
document.write(arrayToBeShown[a]+"<br>");
}
}
document.write("<b>Original Array: (Input)</b>" + "<br><br>");
showDataByRow(createSampleArray());
document.write("<br><br><br>");
var sortColumnArray = new Array('0','1','3'); 

document.write("<b>Sorted Array: (Output)</b><br>Order: First column, then by second column and then by Last Column" + "<br><br>");
showDataByRow(do2DArraySort(createSampleArray(),sortColumnArray));
</script>
</body>
</html>
When the above code is executed, this will show the input table array and output table array as shown below. Original Array: (Input)
Ashley,13,Male,Texas
Smith,32,Male,Colorado
Jane,21,Female,South Carolina
Anna,12,Female,Maryland
Ashley,13,Male,Delaware
Ashley,46,Male,Newyork
Sorted Array: (Output) Order: First column, then by second column and then by Last Column
Anna,12,Female,Maryland
Ashley,13,Male,Delaware
Ashley,13,Male,Texas
Ashley,46,Male,Newyork
Jane,21,Female,South Carolina
Smith,32,Male,Colorado
Enhancements: 1. The code can be enhanced to accomodate sort order for each of the sort columns by having a seperate array to specify that.
2. It can be relooked for performance improvements and enhanced variable handling.
3. There are few issues related to null/empty-value, if it exists in any of the columns being sorted.


Note: The objective of this article is to assist in learning the Javascript array concepts and it's usage. This code is not intended to be used for production purposes as it is not written with that aspect in mind. So, if you want to use it, use it at your own risk.

No comments:

Post a Comment