Sort and Display Data Stored in Arrays

Sort and Display Data Stored in Arrays

How do I sort columns with their corresponding rows of information and then add data? I would like to use the data in a Web page.


If you are using client-side JavaScript, you can store the data in arrays, then sort the arrays and regenerate an HTML table to display the newly sorted data. You will store each column’s worth of data in a separate array. Also, associate an “onclick” event with each column of the table and with a procedure that will execute and sort the array that is associated with that column (the one that was clicked).

Further, you must sort all other arrays in exactly the same order as the first so that all rows stay together. Use a simple sort routine, such as a bubble sort, to sort the first array, and include code that will move elements of all other arrays when an element of the first array is moved. The sort will look something like the following code. This code assumes that you have three arrays of data that will be displayed in columns of the table.

function bubbleSort(x, lim){	var i	var k	var temp		for(i=0; i x[k+1])			{				// Normally, we would use code like this, but since				// we are working with 3 arrays that must be 				// sorted together, use the next blocks of code				/*				temp=x[k]				x[k]=x[k+1]				x[k+1]=temp				*/								temp=Ages[k]				Ages[k]=Ages[k+1]				Ages[k+1]=temp								temp=Colors[k]				Colors[k]=Colors[k+1]				Colors[k+1]=temp								temp=Weights[k]				Weights[k]=Weights[k+1]				Weights[k+1]=temp			}		}	}}

Finally, you will completely re-generate the table. You will create a variable and concatenate an entire

tag and all the rows and columns (tags) of your table. If you are using IE, you can use a tag pair and set its innerHTML property of that to the value of your variable (holding the
tags and associated data). Remember to concatenate the newly sorted data from the arrays in the table. If you are using Netscape Navigator, you can do essentially the same thing with layers instead of a span.


Share the Post: