Array Object

An array is an object that contains a collection of data. You can create arrays of various data types. They can be in numbers, Strings, boolean or they can be mixed. An array has a length property and various methods, which we will look at later on.


Declaring an Array


Initialising an Array

Once an array has been declared the next step is to initialise the array. We have already declared an array called subject that has 3 elements (see above declaring an array).

The value inside an array is called an element and the position of each element is recognised by its index number [n], which starts at 0. Maths is the first element [0], English is the second element [1] and Biology is the third element [2].


<script>
var subject=[3];
subject[0]="Maths";
subject[1]="English";
subject[2]="Biology";

<script>
Index Value
0 Maths
1 English
2 Biology


You can declare and initilaise an array right at the beginning:


Change an Array value

Let's change the value of English to French. We know the index of English is the second element[1].

Before:

Index Value
0 Maths
1 English
2 Biology
<script>
subject[1]="French";
</script>

After:

Index Value
0 Maths
1 French
2 Biology



Property

An array object has a property called length, which determines the number of elements in an array. The name of the array is followed by a dot and the word length .


Syntax

nameOfArray.length

Example:

<script>
var cake = new Array(6);
document.write(cake.length);
</script>

Displays




If you click the button "click me" it allows you to enter an array of 6 numbers or strings, which are then printed on to the text box.






Method

Methods are doing words (verbs) such as running, walking and talking; they are tasks that are carried out by the computer.


Syntax

nameOfArray.method()



Some of the methods have arguments inside the parentheses.


sort()

The sort method sorts the elements of an array into alphabetical order but it has problems sorting numbers.

First of all, let us sort an array of colours into alphabetical order before we look at numbers.


<script>
var colours=new Array("red","green","orange");
document.write(colours.sort());
</script>

Displays



Now let us look at numbers!

<script>
var numbers =new Array(33,46,21,58,72);
document.write(numbers.sort());
</script>

Displays



They seem to be sorted out ok! So what is the problem?

The problem occurs when you have numbers such as 5,9,23,102,45. Let's see what happens when we try to sort these numbers out.


<script>
var nums =new Array(5,9,23,102,45);
document.write(nums.sort());
</script>

Displays


As you can see the first number is 102 because the sort method recognises the first digit 1. The second number is 23 because the first digit is 2, so how do we overcome this problem?

We have to create a function that compares two numbers. Therefore, let us create a function called compareNum with two arguments, inside the parentheses, called a and b. The compareNum function will then be passed into the sort method's parentheses.


Function

<script>
function compareNum(a,b)
{
return a-b
}
</script>
<script>
var nums =new Array(5,9,23,102,45);
//compareNum passed as an argument
document.write(nums.sort(compareNum));
</script>

Displays




concat()

The concat combines two arrays into a single array.

<head>
<script>
var shoeSize= new Array(3,4,5);
var color=new Array("red","green","blue");
var shoe=shoeSize.concat(color);
document.write(shoe);
</head>
<script>

Displays






As you can see the arrays shoeSize and color have been combined into one array called shoe.



join()

The join method joins all the elements of an array in to a string. Each element is separated by a separtor such as a comma, which is the default.

<script>
var color=["red","orange","green","blue"];
document.write(join.color());
<script>

Displays



If you do not want the comma as the separtor you can select a string of your choice. Let's create different string separtors for an array called age.

<script>

var age=["18","24","35","43"];
document.write(age.join("*")+"<br>"<br>");
document.write(age.join("&")+"<br>"<br>");
document.write(age.join("!")+"<br>"<br>");
<script>

Displays



push()

The push() method allows you to add one or more elements to the end of an array and returns the value of the new array length.

<head>
<script>
var names= new Array("Jane","Imran","Tom");
document.write("Length is:" + names.length);
document.write("<br><br>);
document.write("Add Nadia and Lee")
document.write("<br><br>");
document.write("Length changes to:" + names.push("Nadia","Lee"));
document.write("<br><br>");
document.write("Print names: " + names);
</head>
</script>



Displays



We started of with 3 names in the array and used the push() method to add on two more names. Now the new length of the array is 5.



You can also use the length property to add an element. Let us add silver to the array called colours. The array already has the colours blue, red and pink.


<script>
var colours= new Array("blue","red","pink");
document.write((colours));
document.write("<br><br>");
colours[colours.length]="silver"
document.write((colours));
</script>

Displays





pop()

The pop() method removes the last element of an array, which changes the length of the array.


<script>
var numbers= new Array(66,5,8,32);
document.write("Before: " + numbers);
document.write("<br><br>");
document.write("Element removed was:")
document.write (numbers.pop());
document.write("<br><br>");
document.write("After: " + numbers);
<script>

Displays



shift()

The shift() method removes the first element of an array.

<script>
var drinks= new Array("tea","milk","water");
document.write("Before:" + drinks);
document.write("<br><br>");
document.write("Removed " + drinks.shift());
document.write("<br><br>");
document.write("After:"+ drinks);
</script>

Displays



unshift()

The unshift() method adds one or more elements to the front of an array and returns the new length.

<script>
var countries= new Array("India","Italy","Spain,"Canada");
document.write("New length:")
document.write(countries.unshift("Australia","Germany")
document.write("<br><br>");
document.write("Print countries:" + countries);
<script>


Displays




slice()

The slice() method extracts a part of the array and returns a new array.

Inside the parentheses you can have an argument, in integer, called the start index or you can have two arguments the start and the end index (optional).

Note: When we use the start and end index to extract a part of the array the end element is never included.

If we look at the example below the start index is 0 and the end index is 3. Therefore, all the elements starting from 0 up to 3 are extracted. The end element 3, which is 'd' is not extracted.


<script>
var examGrade = ["a","b","c","d","e","f"];
document.write(Passed Grades:)
document.write(examGrade.slice(0,3));
<script>

Displays



Lets use the slice() method to extract different parts of an array.

<script>
var examsGrade = ["a","b","c","d","e","f"];
"//extracts from d to f "
document.write("1. "+ examGrade.slice(3));

"//extracts from c to d"
document.write("2. "+ examGrade.slice(2,4)

"//extracts from b to e"
document.write("3. "+examGrade.slice(1,-1));
<script>

Displays

The end index -1 would be f, so it would not be extracted.



splice()

The splice() method allows you to insert and remove elements from anywhere in an array.

Syntax

nameOfArray.(startPosition,totalNumber,value1,value2...);


The first argument points to the startPosition in the array, this is where you want to start inserting or removing elements from.

The second argument totalNumber is the number of elements to be deleted.

The arguments value1, value2 and so on are the values of the new elements that are being inserted.

The array length will keep changing everytime you insert or remove an element.

If you only want to insert an element than the totalNumber argument should be 0.



<script>
var numbers = ["1","2","23","3","6"];

//remove 23 document.write("Remove Number:")
document.write(numbers.splice(2,1));
document.write(numbers);

//insert 5 and 10
document.write(numbers.splice(3,0,"10","5"));
document.write(numbers);
<script>

Displays




reverse()

The reverse() method does exactly what it says. It reverses the order of the elements in an array. The last element becomes the first and so on.

Syntax

nameOfArray.reverse();



<script>
var characters = ["a","b","c","d","e"];
document.write("Before:"+characters);
document.write("<br><br>");
document.write("Reversed:")
document.write("characters.reverse());
<script>

Displays




toString()

The toString() method converts the elements in an array to a string.

<script>
var cars= ["volkwagen","ford","honda"];
document.write(cars.toString());
<script>

Displays



Access an array

The index is used to retrieve an element from an array. In the example below the for loop can be used to access all the elements in an array.


<script>
var flowers=new Array("Rose","Tulip","Iris");
document.write("Array length is ")
document.write(flowers.length ");
document.write("<br>""<br>")
document.write("Name and Index:" )

document.write("<br>""<br>")
for (var i=0; i<flowers.length;i++)
{
document.write(flowers[i]+" [" + i + "]);
document.write("<br>""<br>");
}
</script>

Displays






Now do the Exercises!