JavaScript Arrays

Table of content:

What are arrays and why are they useful

An array is a way or storing similar type of data for later access. An array is a user-defined object and they are accessed differently that
other objects are accessed.

An array uses a single variable name to store multiple values. They can be accessed using an index number or in the case of the associative arrays using just a string.

For example if you want to print the name of all students of a class you can use arrays. You could use regular variables to store the names of the students then type into a document.write() method the names of the variables, but that will take a very long time. Instead you could use an array to store the students’ name and access it easily using a loop.

Naming, defining, and accessing arrays

Naming an array

The rules for naming arrays are the same as for naming variables, functions, and objects. You have to avoid the following three things: numbers in the first character, spaces, and reserved words.

Defining an array

Defining an array is very similar to creating an instance of an object.


var ArrayName = new Array(element0,element1);

You replace ArrayName with the actual name you want to give to your array, and element0 and element1 with the values that each element will have.


var StudentsClass = new Array("Tra","Sonia","Dan","Catalin");

The names of the students are stored inside an array that has four elements. The names are between quotation marks because they are strings.

Accessing an array’s element

Accessing array elements is usually done with an index number. Basically, the index number is the element’s position in the array.


var VariableName = ArrayName[0];

Note:
Arrays begin storing values with the number 0 rather than 1.

You would replace VariableName with the name you want to give to the variable and the ArrayName with the name of the array you want to access. [0] is the first element in the array.


//Assigning the array's element to a variable
var StudentsClass = new Array("Tra","Sonia","Dan","Catalin");
var VnStud = StudentsClass[0];
document.write("The Vietnamese student in the class is "+VnStud);

//Without assigning the array's element to a variable
var StudentsClass = new Array("Tra","Sonia","Dan","Catalin");
document.write("The Vietnamese student in the class is "+StudentsClass[0]);

Other ways to define arrays

Space now, assign later

Space now, assign later method allows you to assign a certain amount of space (or elements) to an array and then, later in the script, assign the values.


var StudentsClass = new Array(4);

This creates an array called StudentsClass which will initially have four elements (you can add more elements later).

If you want to assign a value of “Dan” to the third element in the array then you use index number (index number 2 for third position).


StudentsClass[2] = "Dan";

You can add more elements to the initial array and give them values.


StudentsClass[4] = 'Flora";

This adds the fifth element, which has a value of “Flora” to the array.

Space now, assign numerically now

In Space now, assign numerically now method some or all of the elements of the array are assigned right after the array is created.


var StudentsClass = new Array(4);
StudentsClass[0] = "Tra";
StudentsClass[1] = "Sonia";
StudentsClass[2] = "Dan";
StudentsClass[3] = "Catalin";

This method is very useful for long lists of elements.

Array name, no parameters

The Array name, no parameters method, as the name suggests, allows you to create an array with no elements in it. You can add one or more elements to the array later in the script.


var StudentsClass = new Array();
//Here can go whatever another JavaScript code you want
StudentsClass[0] = "Tra";

You can assign a value to the element number 3 for example. In our case, where we have an array with no elements, means that the array will have now three elements. You can assign values for the other elements later in the script.


var StudentsClass = new Array();
//Here can go whatever another JavaScript code you want
StudentsClass[2] = "Dan";

Properties of the array object

An instance of a JavaScript Array object is able to use various properties and methods of the Array object. You access the properties by using the array name followed by the property or method name you want to use.

The table below lists the properties of the Array object with a short description of each.

Property Description
constructor Refers to the constructor function used to create an instance of an object.
index Used when an array is created by a regular expression match.
input Used when an array is created by a regular expression match.
length Contains a numeric value equal to the number of elements in an array.
prototype Allows the addition of properties and methods to abjects such as the JavaScript array object.

The constructor property

The constructor property contains the vaue of the function code that constructed an array. It is mainly used for information or comparison.


function Array() {
[native code]
}

To access the property you use the array name followed by the dot operator and the constructor keyword.


arrayname.property

Of course you must replace arrayname and property with the actual names of the array and the property you want to use.


var StudentsClass = new Array(4);
document.write(StudentsClass.constructor);

The above code will output function Array() { [native code] } which is the constructor function of the array.

The index and input properties

The index and input properties require a deep understanding of regular expressions. The explanation related these two properties can be found on “Handling strings” on this website.

The length property

The length property returns a number that tells you how many elements are in an array. It is useful when using loops to cycle through arrays. To use the length property you use the name of the array and then add the length property.


var StudentsClass = new Array(4);
document.write("The array has "+StudentsClass.length+" elements");

The output will be “The array has 4 elements”.

The prototype property

The prototype property allows you to add properties and methods to an object that already exists, in our case an Array object.


Array.prototype.NewProperty = DefaultValue;

The NewProperty will be replaced with the name you want to use for the new property and the DefaulValue with the default value you want that property to have.


Array.prototype.attitude = "amazing";
var StudentsClass = new Array();
document.write("This class is "+StudentsClass.attitude);

The output will be “This class is amazing”.

The addition of a new property like this affects every array in the document afterward. If you want to use prototype property with two arrays on the page and the first array to print on the page the default value while the second array to print a new value then you might use something like this:


Array.prototype.attitude = "amazing";
var StudentsClass = new Array();
document.write("This class is "+StudentsClass.attitude);

var AnotherClass = new Array();
AnotherClass.attitude = "not so amazing";
document.write("The class next to it is "+AnotherClass.attitude);

As you can see, the second array uses the attitude property but it doesn’t keep it’s value, it changes it to “not so amazing”.

Methods of the array object

The table below lists the methods of the Array object and provides a short description of each method.

Method Description
concat() Combines the elements of two or more arrays in one new array.
join() Combines the elements of an array into a single string with a separator character.
pop() Removes the last element of an array and then returns it if needed.
push() Adds elements to the end of an array then returns (if needed) the new length value of the array.
reverse() Reverses the direction of the elements in an array.
shift() Removes the first element of an array and then returns it if needed.
unshift() Adds elements to the beginning of an array then returns (if needed) the new
length value of the array.
slice() Pull out a specified section of an array then returns the section as a new array.
splice() Removes or replaces elements in an array.
sort() Sorts the elements of an array in alphabetical order based o the string values of the elements.
toString() Combines the elements of an array into a single string with a comma as a separator character.

The concat() method

The concat() method is used to combine the elements of two or more array and return a new array containing all of the elements.


var Motorbikes = new Array("Yamaha" , "Suzuki");
var Cars = new Array("BMW" , "Audi");

var Autovehicles = Motorbikes.concat(Cars);
document.write(Autovehicles);

First I have created two arrays, each containing two elements. Then, using concat() method, I combined the elements of the two arrays into one new array named Autovehicles. First in the new array are the elements of the Motorbikes array followed by the element of the Cars array. If you take a look at the code you will know why. In the following example the elements of the Cars array are first then followed by the elements of the Motorbikes array.


var Motorbikes = new Array("Yamaha" , "Suzuki");
var Cars = new Array("BMW" , "Audi");

var Autovehicles_2 = Cars.concat(Motorbikes);
document.write(Autovehicles_2);

You use the array of which elements you want to appear first in the new array to call the concast() method and send the second array as paramether so you get its elements in the new array after the elements of the array that called the concat() method.

If you conbine three or more arrays then the elements in the new array are ordered as follow:

  • The elements of the array used to call the concat() method.
  • The elements of the arrays that are sent as parameters in the order in which they are sent.


var Motorbikes = new Array("Yamaha" , "Suzuki");
var Cars = new Array("BMW" , "Audi");
var Planes = new Array("Boeing" , "Airbus");

var Autovehicles = Motorbikes.concat(Cars , Planes);
document.write(Autovehicles);

The output of the above code will be “Yamaha,Suzuki,BMW,Audi,Boeing,Airbus”.

The join() method

The join() method is used to combine the elements of two or more arrays into one string. The elements in the string are separated by a character sent to the method as parameter. A comma is used by default if no parameter is sent.


var Animals = new Array("dogs" , "cats" , "chickens");
var AnimalsString = Animals.join();
document.write(AnimalsString);

If you want the elements in the string to be separate by a separator character (|) then you send it to the join() method as a parameter.


var Animals = new Array("dogs" , "cats" , "chickens");
var AnimalsString = Animals.join("|");
document.write(AnimalsString);

The pop() method

The pop() method is used to remove the last element from an array. If you assign the result of the pop() method to a variable then the popped element will be assigned to the variable.


var Animals = new Array("dogs" , "cats" , "chickens");
var FavoriteAnimal = Animals.pop();
document.write("My favorite animals are "+FavoriteAnimal);

The code creates an array named Animals that contains three elements. The second line assigns the last element of the Animals variable to a new
variable named FavoriteAnimal using the pop() method.

The push() method

The push() method is used to add elements to the end of an array. The parameters sent to the method are the new element(s) you wish to add to the array.

Note:
The value returned by the push() method in older browsers is the last element that has been added to the array. In newer browsers is the numeric value of the new length of the array.


var Fruits = new Array("bananas" , "apples");
Fruits.push("grapes");

The code adds a new element to the array using the push() method. Now, the array contains three elements.

You can assign the result to a variable and it will return the numerical value.


var Fruits = new Array("bananas" , "apples");
Fruits.push("grapes");
var MoreFruits = Fruits.push("pears", "mangoes");
document.write("It returns "+MoreFruits+" fruits");

The output of the code will be “It returns 5 fruits”.

The reverse() method

The reverse() method is used to reverse the order of the elements in an array. It is not necessary to send parameters or return values from it.


var Fruits = new Array("bananas" , "apples" , "pears", "mangoes");
document.write(Fruits);
Fruits.reverse();
document.write("<br>"+Fruits);

The shift() method

The shift() method removes the first element of an array. It returns the value of the elements that was removed.


var Fruits = new Array("bananas" , "apples" , "pears", "mangoes");
document.write(Fruits);
Fruits.shift();
document.write("<br>"+Fruits);

You can assign the value of the method to a variable so you can use it later.


var Fruits = new Array("bananas" , "apples" , "pears", "mangoes");
var FavoriteFruit = Fruits.shift();
document.write(FavoriteFruit);

The unshift() method

The unshift() method is used to add elements to the beginning of an array. The elements are sent as parameters to the method. The value returned by the method is the numeric value of the new length of the array.


var Fruits = new Array ("pears", "mangoes");
Fruits.unshift("bananas" , "apples");
document.write (Fruits);
var NumberFruits = Fruits.unshift();
document.write("<br>Now there are "+NumberFruits+" fruits in the array");

The output will be “bananas,apples,pears,mangoes Now there are 4 fruits in the array”.

The slice() method

The slice() method is used to slice a specific section of an array then to create a new array using the elements from the sliced section of the old array.


var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples");
var FewFruits = Fruits.slice(1,3);
document.write(FewFruits);

Initially, an array that contains four elements is created. On the second line of code, using slice() method, the second and the third element are eliminated (index 1 eliminates the second element in the array and index 3 represents the first element that won’t be eliminated). The last line of code writes on the document the elements of the new array.

The output will be “mangoes,bananas”.

The splice() method

The splice() method is used to remove or replace element in an array.


var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples");
var FewFruits = Fruits.splice(2,1);
document.write(Fruits);
document.write(" | "+FewFruits);

On the first line a new array with four elements is created.

On the second line a new array is created using splice() method. What is (2,1)? “2” represents the index of the element from where to start removing elements and “1” represents the number of the elements to be removed. The element with the index 2 is the third element which is “bananas”. Since only one element will be removed that means only the element “bananas”. If you want to remove two elements then you can use (2,2) instead of (2,1). This will remove the elements “bananas” and “apples”.

The third line write on the document elements of the initial array without the element that was removed (bananas).

The fourth line writes on the document the element of the new array formed with the removed element (bananas).

You can use splice() method to replace the spliced elements in an array or just to add elements to an array.


var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples");
var FewFruits = Fruits.splice(2,1,"grapes");
document.write(Fruits);

The code replaces the “banana” element with the “grapes” element.

If you just want to add an element to the array and not removing any then just set the first parameter at the index number you want to begin adding the new elements and the second parameter to “0” since you don’t want to remove any element.


var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples");
var FewFruits = Fruits.splice(2,0,"grapes" , "watermelons" , "pineapples");
document.write(Fruits);

The three new elements will be added to the array just before the element with index number 2, which is “bananas”. No element of the array will be removed since the second parameter is set to “0”. The output will be “pears, mangoes, grapes, watermelons, pineapples, bananas, apples”.

The sort() method

The sort() method is used to sort the element of an array in alphabetical order.


var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples");
Fruits.sort();
document.write(Fruits);

This will output the elements of the array in alphabetical order “apples, bananas, mangoes, pears”.

The toString() method

The toString() method combines the elements of an array into a single string with a comma as a separator character.


var Fruits = new Array ("pears", "mangoes" , "bananas" , "apples");
Fruits.toString();
document.write(Fruits);

Extended array methods

JavaScript 1.6 or higher supports additional methods that can be used. However, they might not be cross-browser. The methods are listed in the table below.

Method Description
filter() Returns a new array that contains elements from an array that returned true
based on the function used to filter it.
forEach() Calls a specified function for each element in the array.
every() Returns true if all elements in the array return true for a specified function used to test them.
indexOf() Returns the lowest index number for an element that has a value equal to the
specified value sent as parameter.
lastIndexOf() Returns the highest index number for an element that has a value equal
to the specified value sent as parameter.
map() Returns a new array that results from calling a specified function on every element in the array.
reduce() Runs a function on two values in the array at a time, from left to right
until just a single value is left.
reduceRight() Runs a function on two values in the array at a time, from right to left
until just a single value is left.
some() Returns true if one or more elements return true for the specified function used to test them.

Using arrays with loops

Loops allow you to move through an array’s elements without the need to deal with each element in part. This is useful because it saves you time when you deal with big arrays.

Creating array elements

A loop can be of a real help in creation of the elements of an array.

For example, if you need to input the names of students of a class then you can use a for loop.


var NumberUser = new Array(4);
for (var count=0 ; count<4 ; count++) {
NumberUser[count] = window.prompt("Enter your name" , "");
}

First, this code creates a new array that has four elements. The for loop is used to assign each element in the array a value.

The loop starts by setting the loop’s count variable to 0 and it will run until the expression count<4 is no longer true.

The count variable will have the value of 0 first time. The value increases by 1 since the count++ adds 1 to the value each time, therefor the value second time will be 1, the third time will be 2, and the forth time will be 3. It won’t be a fifth time because that means count will be 4 and it has to be less than 4.

A value is assigned to the element at the index number represented by the count variable each time through. The value that is assigned is what the viewer types in when the prompt appears. In our case the viewer gets four prompts.

Assigning values to elements of an array with loops can be really useful when you want an element value to affect each other element of the array.


var NumberEven = new Array(5);
var StartsCount = 0;
for (var count=0 ; count<10 ; count+=2) {
NumberEven[StartsCount] = count+2;
StartsCount ++;
}

On the first line an array with five elements is created.

On the second line, a new variable is declared, which will hold a count incremented by 1.

On the third line the for loop will increment by 2 from 0 to 8.

The forth line assigns elements to the array based on the value of the count variable.

On the fifth line the StartsCount variable is incremented.

The count is increased by 2 to ensure that an even number is used for calculation.

Moving through arrays

You can cycle through an array that has been created in order to change it, gain information from it, or list its content.


var StudentsNames = new Array();
StudentsNames[0] = "Dan";
StudentsNames[1] = "Tra";
StudentsNames[2] = "Sonia";
StudentsNames[3] = "Flora";

for (var count=0; count document.write(StudentsNames[count]+ "<br>");
}

First line creates the new array then on lines 2-5 each element of the new array is assigned a value. The for loop is used to print on the screen the elements of the array.

The use of cont<StudentsName.lenght is beneficial since the array can be adjusted to any number of elements. The loop will cycle through until the full array is used.

If you want the array sorted in alphabetical number then just add StudentsNames.sort(); to your code just after the last element of the array.

An easier way of achieving the same result:


var StudentsNames = new Array();
StudentsNames[0] = "Dan";
StudentsNames[1] = "Tra";
StudentsNames[2] = "Sonia";
StudentsNames[3] = "Flora";

for (student in StudentsNames) {
document.write(StudentsNames[student] + "<br>");
}

Using associative arrays

Associative arrays (also known as hash tables) allows you to use strings instead of index numbers.

Using associative arrays is more limited but they make the elements of the array easier to remember.


var StudentsClass = new Array();
StudentsClass["tall"] = "Dan";
StudentsClass["beautiful"] = "Sonia";
StudentsClass["smart"] = "Tra";
StudentsClass["cute"] = "Flora";

The code above creates a blank array and gives it values by assigning values to elements. Each element is given a string in the place of its index number. The value of the string used instead of the index number is something that is meaningful and easily associable with the value of the element of the string.

You can access an associative array in the same way you access a normal array.


StudentsClass["tall"]

If you want to print on the screen the list of the students then you could use:


var StudentsClass = new Array ();
StudentsClass["tall"] = "Dan";
StudentsClass["beautiful"] = "Sonia";
StudentsClass["smart"] = "Tra";
StudentsClass["cute"] = "Flora";

document.write("The tallest student in the class is "+StudentsClass["tall"]+".<br>");
document.write("The most beautiful student in the class is "+StudentsClass["beautiful"]+".<br>");
document.write("The smartest student in the class is "+StudentsClass["smart"]+".<br>");
document.write("The cutest student in the class is "+StudentsClass["cute"]+".<br>");

Leave a Reply