JavaScript: Basic, Multi-Dimensional & Associative Arrays

Arrays are an amazingly useful variable in all programming languages, they allow you to store vast amounts of organised data in just one reference. This helps not only on software memory usage and speed – But also on program complexity and code neatness.

I’m going to explain by example many different ways you can define and read an array in JavaScript, and believe me, there are a number of methods.

Arrays - Basics

To define an ordinary array in JavaScript is very simple. There is no fancy attributes or methods you need to call, it’s as simple as defining a normal variable:

var myArray = [];

You will notice that you have not had to tell JavaScript how many items are going to be in your array, unlike other languages, JavaScript automatically expands the array as needed and you never need to worry about defining or extending the size of the array.

However you can use the “old” method which allows you to define the arrays initial size, but it is recommended that you use the above method:

var myArray = new Array(10); //Creates an empty array with 10 elements

If you need to define a pre-populated array then this is also really simple:

var myArray = [12, 24, 48];

And if you need to use strings in the array…

var myArray = ["London", "Cannock", "Scotland"];

You can even mix the types in the array, as JavaScript doesn't care about type casting Smile:

var myArray = ["London", 32, "Cannock", 845];

Arrays – Multi-Dimensional

Sometimes you need to use more complex arrays, arrays within arrays are a very common practice in programming and they are just as useful as arrays themselves. Such arrays are referred to as multi-dimensional arrays, and can be defined in JavaScript like this:

var myArray = ["hello", ["stuff", "grouped", "together"], "world"];

Above is a very basic example of a multi-dimensional array, only going deep by one level – basically you group values into [ ] brackets to define an array within the array, say you wanted to get “grouped” from the above example, it is located at index 1 of the main array, and index 1 of the inner array – so you would access it as follows:

alert(myArray[1][1]);

To get “world” is even simpler:

alert(myArray[2])

Here is a final example of a much more complex multi-dimensional array – with example outputs to hopefully show how it works (note how I have also laid out the array so that it is easy to read):

var myArray = [
 "hello", 
 ["berries", "grouped", 88, "frozen"], 
 [
 "stuff", 
 [
 "mash", 
 ["melon", "freeze", 12, "together"], 
 "people"
 ], 
 "car"
 ], 
 [
 "orange", 
 "code", 
 84, 
 ["mate", "women", "man"]
 ], 
 ["bus", "car", 345, "lorry"], 
 "world"
 ];
 
alert(myArray[0]); //hello
alert(myArray[1][2]); //88
alert(myArray[2][1][1][1]); //freeze
alert(myArray[2][2]); //car
alert(myArray[3][3][1]); //woman
alert(myArray[5]); //world

Arrays – Associative

Sometimes it can be a real pain drilling through your array using index numbers, they are meaningless and can make referencing into multi—dimensional arrays difficult and somewhat confusing. So to give your array some meaning you can define “keys” for your arrays so that accessing them is more meaningful to yourself and to your fellow programmers, this is done by using the { } brackets and defining an index name. Note: These are in fact called objects and officially JavaScript does not support associative arrays, however using objects emulates this pretty well and as such is referred to as associative arrays.

A simple Associative array is defined and used as follows:

var myArray = {
 customer :
 ["tom", "dick", "harry"],
 age :
 [23, 42, 18]
 };
 
alert("First customer '" + myArray['customer'][0] + "' is " + myArray['age'][0] + " years old."); //first customer
alert("First customer '" + myArray['customer'][1] + "' is " + myArray['age'][1] + " years old."); //second customer
alert("First customer '" + myArray['customer'][2] + "' is " + myArray['age'][2] + " years old."); //third customer

If you are really into complex arrays then how about a multi-dimensional associative array? Ugghhh yesss that is a turn on…

var myArray = {
 customer :
 [
 {
 firstname : "tom",
 lastname : "smith",
 age : 23
 },
 {
 firstname : "dick",
 lastname : "head",
 age : 42
 },
 {
 firstname : "tom",
 lastname : "thumb",
 age : 18
 }
 ],
 location :
 {
 england : 
 {
 main : "Warwick",
 second : "Cannock",
 third : "London"
 },
 france : 
 {
 main : "Alsace",
 second : "Corsica",
 third : "Provence"
 }
 }
 };
 
alert("First customer '" + myArray['customer'][0]['firstname'] + " " + myArray['customer'][0]['lastname'] + "' is " + myArray['age'][0]['age'] + " years old."); //first customer
alert("First customer '" + myArray['customer'][1]['firstname'] + " " + myArray['customer'][1]['lastname'] + "' is " + myArray['age'][1]['age'] + " years old."); //second customer
alert("First customer '" + myArray['customer'][2]['firstname'] + " " + myArray['customer'][2]['lastname'] + "' is " + myArray['age'][2]['age'] + " years old."); //third customer

//locations
alert(myArray['location']['england']['main']); //Warwick
alert(myArray['location']['england']['third']); //London
alert(myArray['location']['france']['third']); //Provence

If that doesn't make your heart stop then you are a brave programmer, but to be fair, once you get to grips with how JavaScript defines arrays it’s probably the easiest language for arrays around.

Functions + Regular Expressions in arrays

I will leave this post with one final bombshell – functions in arrays! omg omg omg:

var myArray = [ 
 3, 
 'hello!', 
 function() {return 5}, 
 {
 color : 'blue',
 budget : 25
 }, 
 /[ell]/i 
 ];
document.writeln('0>'+myArray[0]+'<BR>');   // Will output: 0>3
document.writeln('1>'+myArray[1]+'<BR>');   // Will output: 1>hello!
document.writeln('2>'+myArray[2]()+'<BR>');  // Will output: 2>5
document.writeln('3>'+myArray[3].color+'<BR>');  // Will output: 3>blue
document.writeln('3>'+myArray[3].budget+'<BR>');  // Will output: 3>25
document.writeln('4>'+myArray[4].test(myArray[1])+'<BR>'); // Will output: 4>true

 

Please feel free to leave feedback / comments / suggestions and/or ask for support using the comment box below.

 

Update (03/03/15) - Comma was missing in example code.

Facebooktwitterredditpinterestlinkedinmail
Author: Dean WilliamsI'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
,
5 1 vote
Article Rating
Subscribe
Notify of
5 Comments
Inline Feedbacks
View all comments

Thanks for this post. Great job. Had a multidimensional associative array like this:

var fruit = [{'number':'1','value':'apples'},{'number':'2','value':'grapes'},{'number':'3','value':'cherries'},{'number':'4','value': 'peaches'}];

For the life of me, couldn't get the syntax right to be able to select the fruit based on the number, and I searched everywhere. This did the trick where 3 is the index number of the object .

var selection = fruit[3]['value'];

The selection would be peaches. Seems simple enough now. Don't know why I couldn't work it out, but I couldn't. Thanks so much.

Thank you for taking time for some people like me :)
I tried your code and notice you forgot
- a comma
} [[insert_comma_here]] france : {

- to modify the alert in bottom
myArray['customer'][2]['firstname']
myArray['customer'][2]['lastname']
myArray['age'][2]['age']

Then you see a JS error because of missing " myArray['customer'][2]['age'] "