Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Introduction to arrays, sorting arrays

An introduction to JavaScript arrays, how to create and access arrays. Also shows you how to use the sort() method to sort both string and number arrays.

On Saturday, July 30th 2005 at 12:55 PM
By Andrew Pociu (View Profile)
****-   (Rated 3.5 with 6 votes)
Contextual Ads
More JavaScript Resources
Advertisement
Both arrays and variables store data. However, arrays store data differently, using elements. Each element of the array can store its own data, just like a variable, thus you can say arrays are collections of variables. Items can be added and removed from the array at any time, also their value can be changed easily. One other feature of the arrays, which is specific to JavaScript is that the elements in the array can be of different types. For example in an array you can have both a string and an integer.



Let's see how we can create an array containing Microsoft's latest operating systems:





<script type="text/javascript">

var OperatingSystems = new Array();

OperatingSystems[0] = "Windows 95"

OperatingSystems[1] = "Windows 98"

OperatingSystems[2] = "Windows Me"

OperatingSystems[3] = "Windows 2000"

OperatingSystems[4] = "Windows XP"

OperatingSystems[5] = "Windows 2003"

OperatingSystems[6] = "Windows Vista"

</script>




An array is declared similar to a variable, using the var keyword, but also assign it to new Array();. This lets JavaScript know OperatingSystems is not just a variable, it's an array.

Array's elements are accessed using their index, which starts from 0. That's why we have 7 operating systems in the array (and 7 elements), but since they're counted from 0, we end up with the 7th element having index 6.



Now let's see how we can access the elements:





<script type="text/javascript">

document.write("The " + OperatingSystems[4] + " operating system is the predecessor of the new " + OperatingSystems[6] + " operating system.")

</script>



See this code in action



The following line along with the declaration of the array will result in the following string:



The Windows XP operating system is the predecessor of the new Windows Vista operating system.



We can do many other things using an array, like loop through it:





<script type="text/javascript">

for(var i = 0; i < OperatingSystems.length; i++)

{

   document.write("At index " + i + " we have " + OperatingSystems[i] + "<br />");

}

</script>



See this code in action



Looping through arrays is a common thing, and one of the main advantages of arrays. We initialize a variable, i, and set it to 0. We increment it with each loop until it reaches the length of the OperatingSystems array. We can get the length of an array using the length property. In our case the length property returns 7 (the number of elements the array has).



JavaScript arrays don't have a fixed size, you can add as many elements as you want inside an array. However, you sometimes may want to define a size for the array, so that you can limit the number of elements the array can store. You can do this when defining the array, in the example below we limit the OperatingSystems array to 10, this way you won't be able to add more than 10 operating systems into the array:





<script type="text/javascript">

var OperatingSystems = new Array(10);


</script>



Also, there is a different way you can use to define an array. In the example below the elements are added in the array right when the array is initialized:





<script type="text/javascript">

var OperatingSystems = new Array("Windows 95", "Windows 98", "Windows Me", "Windows 2000", "Windows XP", "Windows 2003", "Windows Vista");


</script>



This way of adding elements to an array has the same result as when adding them separately (like we did in the first example), however when you have really long arrays, it can get annoying.



Sorting arrays


Using the sort() method we can easily sort the elements inside an array.
sort() can sort both arrays of numbers and strings. Let's try this on a new array I defined below.





<script type="text/javascript">

var
Seinfeld = new Array();

Seinfeld[0] = "Jerry Seinfeld"

Seinfeld[1] = "Elaine Benes"

Seinfeld[2] = "George Costanza"

Seinfeld[3] = "Cosmo Kramer"

</script>




We have the characters from the popular show Seinfeld in an array, ordered randomly, and we want to sort them by name. The following line should do it:





<script type="text/javascript">

Seinfeld.sort();

</script>



Now the array is sorted alphabetically, ascending (which is the default). Let's loop through it like we did with the OperatingSystems array and see the order:





<script type="text/javascript">

for(var i = 0; i < Seinfeld.length; i++)

{

   document.write("At index " + i + " we have " + Seinfeld[i] + "<br />");

}

</script>



See this code in action



The result is exactly what we wanted:



At index 0 we have Cosmo Kramer

At index 1 we have Elaine Benes

At index 2 we have George Costanza

At index 3 we have Jerry Seinfeld



Now let's sort some numbers. We create a new array:





<script type="text/javascript">

var
PrimeNum = new Array();

PrimeNum[0] = 19

PrimeNum[1] = 3

PrimeNum[2] = 13

PrimeNum[3] = 7

PrimeNum[4] = 11

PrimeNum[5] = 5

PrimeNum[6] = 29

PrimeNum[7] = 17

PrimeNum[8] = 2

PrimeNum[9] = 23

</script>



This array contains some randomly ordered prime numbers. We want to put them in ascending order, so we use the sort() method and then we loop through the array:





<script type="text/javascript">

PrimeNum.sort();

for(var i = 0; i < PrimeNum.length; i++)

{

   document.write("At index " + i + " we have " + PrimeNum[i] + "<br />");

}



</script>



See this code in action



And the results is...



At index 0 we have 11

At index 1 we have 13

At index 2 we have 17

At index 3 we have 19

At index 4 we have 2

At index 5 we have 23

At index 6 we have 29

At index 7 we have 3

At index 8 we have 5

At index 9 we have 7



Oh boy, what went wrong? Well, sort() sorts by the ASCII value of the character, that's why we first get the numbers that start with 1 (11, 13, 17, 19), then with 2 (2, 23, 29) and then the rest (3, 5, 7). What we need to be able to sort these numbers correctly is a comparison function. Let's see how it looks like:





<script type="text/javascript">

function CompareXY(X, Y)

{

   return X - Y;

}


</script>



It returns the difference between two numbers. How does this help? Well if the returned value is negative, it means X is smaller than Y. If the returned number is positive, it means X is bigger than Y. If the returned value is 0, it means both are equal. Now how we use this function with sort()? Simple:





<script type="text/javascript">

PrimeNum.sort(CompareXY);

</script>



See this code in action




We now have the result we want:



At index 0 we have 2

At index 1 we have 3

At index 2 we have 5

At index 3 we have 7

At index 4 we have 11

At index 5 we have 13

At index 6 we have 17

At index 7 we have 19

At index 8 we have 23

At index 9 we have 29



There are many other things we can do with JavaScript's arrays, that's why this will be continued.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
There are no comments.

Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs JavaScript Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources