JavaScript Data Structures - Array Object
Written by Ian Elliot   
Thursday, 05 January 2017
Article Index
JavaScript Data Structures - Array Object
Acess Methods
Array v Associative Array

datastruct

The Access Methods

As Array is an object, is has some methods that have been added to make it more useful. These make the JavaScript array easier to use in some applications than arrays in other languages.

For example the pop and push methods can be used to remove an item from the end of the array or add an item:

myArray.push("A");

adds A to the end of the array and increases length by 1.

x=myArray.pop();

removes the last element from the array and stores it in x; it also decreases length by 1. You can see that pop and push can be used to implement a stack - see Javascript data structures - Stacks.

Similar to the pop and push methods, the Shift and Unshift methods remove and add items to the start of the array. These two operations are ideal for implementing a queue or deque.

The Array Manipulation Methods

You can work with the Array in JavaScript in ways that are very similar to a string of characters. To understand how these methods work, think of an Array as a string of element rather than characters.

The concat method returns a new array that is the concatenation of two other arrays:

var C=A.concat(B);

stores a new array in C that is the result of putting the Arrays A and B together (with B's elements following A's). You can concat more than two Arrays using A.concat(B,C) etc.

The slice method extracts a sub array from an existing array:

var B= A.slice(1,3);

creates a new array in B that starts at element A[1] and ends at element A[2]. That is slice(s,e) returns the array from element s to element e but not including element e.

Similarly  the splice method can be used to remove or insert elements:

var B=A.splice(3,5);

will create a new array in B with five elements missing started at element 3, You can also specify new values to insert:

var B=A.splice(3,2,"a","b","c");

deletes two elements starting at element 3 and then inserts three elements starting at element 3.

Given these methods handle an array as if it was a type of string, there is also the join method which converts an Array into a string with an optional separator. There is also the very useful string function, split , which will split a string into an Array based on a specified separator character.

Array Ordering Methods

As one of the prime properties of an array is that it stores its elements in a fixed order, there should be methods that change this order.

The reverse method will reverse an array in place, i.e. it actually modifies the array:

A.reverse();

reverses the order of the elements in A.

Similarly sort will put the elements into order:

A.sort();

sorts the elements of A into numerical order.

If the elements of A are not numeric values, then you have to supply an order function that compares its two parameters a and b  and returns -1 if a<b, 1 if a>b and 0 if a=b.

For example to sort strings on string length alone you might use:

A.sort(function(a,b){
 if (a.length<b.length)return -1;

 if (a.length>b.length)return 1;
 
if (a.length=b.length)return 0;

});

 

Object arrays

So far the Array object looks like the sort of array you would meet in any language, but you need to keep in mind that JavaScript isn't typed and what this means is that you can store anything in an array element.

For example

myArray=["A",1,"C",2];

is perfectly reasonable JavaScript and most JavaScript programmers don't find it in the least bit difficult to understand and work with. However in a strongly typed language all of the elements of an array have to be the same type and mixing characters and integers is unthinkable. The reason is that you need to be able to process an Array in a for loop say in a uniform manner - imagine what happens if you add one to every element of myArray?!

Of course the other point of view, i.e. the JavaScript point of view is that it doesn't matter. If you have a need for an Array with mixed elements like this why not add one to each - the integer elements will increment  and the String elements will concatenate. It is the object that determines the meaning of an operator and integers interpret + as adition and Strings as concatenation. 

However, you can also store JavaScript objects in an array and this is where things can become more complicated looking.

For example, you can store an object literal, or any object in an array element:

myArray=["A",{property1:1,property2:2},"C",2];

In this case myArray[1] is an object. This means you can write things like

myArray[1].property1

which evaluates to 1 the value of property1 on the object literal.

Object arrays are incredibly useful and they lead the way to some more sophisticated use of JavaScript. To give you just two common idioms, we have function parameters and function arrays.

Sometimes you need to pass a variable number of complicated things to a function. One way of doing this in a very flexible way is to use an array parameter:

MyFunction(
 [
   {property1:value1,
    property2,value2},

    x,
    y
  ]);

The receiving function can simply process its single parameter as an array with, in this case, the first element an object and the second two numeric values.

Function arrays are useful when you are trying to implement something that responds to an event or condition or when you need to select which function is used by an index.

For example:

var functions=[
 function1(parameters){
               function definition},

 function2(parameters){
               function definition},
 function3(parameters){
               function definition}

]

Now to call the first function you would use

functions[0](arguments);

or to call the ith function

functions[i](arguments);

Multidimensional Arrays

One of the things that can confuse a new JavaScript programmer is - how do you create and use two or more dimensional arrays?

JavaScript doesn't have multidimensional arrays because it doesn't need them. As an Array can have elements which are JavaScript objects you can implement a two-dimensional array as an Array of Arrays.

For example, a 2 x 2 array can be defined as:

var A=[["a","b"],["c","d"]];

The first element of A , i.e. A[0], is ["a","b"] which is usually treated as the first row. To pick out the first element of the row we simply index again ["a","b"][0] which is "a". The double indexing can be done in one go as in:

A[0][0];

The i, j element of the array is:

A[i][j];

Notice that in JavaScript you cannot use the short form

A[i,j];

as you can in many languages.

In JavaScript each index has to be written within its own square brackets.

You can generalize this idea to arrays of any size and dimensionality, but in practice you rarely need more than two dimensions.

In general using a multidimensional array is just as easy as a standard array, but there is one small problem. Normally if you try to use an Array element that hasn't been initialized you simply get an undefined value. In the case of a two-dimensional array, say, the situation is a little worse.

Consider what happens in this case:

var A=[["a","b"],["c","d"]];
alert(A[2][0]);

As there is no A[2] undefined is returned and undefined[0] doesn't make any sense  - the result is a runtime error.

Even more of a problem is that assignment doesn't work either.

If you try

A[2][0]=10;

again you will generate a runtime error rather than creating the element. The problem is that the Array isn't initialized to hold suitable row Array objects. 

The solution is to initialize the rows of the array as follows:

r=4
var A=[]
for(i=0;i<4;i++){
 A[i]=[];
}
alert(A[2][0]);

The variable r sets the number of rows that you want and in this example the array is created with four rows - each an empty array. Now when we try and access A[2] there is an empty array acting as the row and so [][0] makes sense and we get undefined rather than an error. If you try to assign to A[2][0] then this works because again A[2] is an empty array [] and assigning to [][0] creates the element.

You can package the code snippet into a function to set up an array with any number of rows. You can extend the same idea to initialize arrays of arrays of arrays.

datastruct



Last Updated ( Thursday, 05 January 2017 )