Javascript Array: How To Use Arrays in Javascript

Creating and Initializing Arrays In Javascript
Multidimensional Arrays in Javascript
Iterating Through Arrays in Javascript
Javascript Array Sort: Sorting Arrays in Javascript
Pop and Shift: Removing Elements From Arrays in Javascript
Javascript Slice: Selecting Part of an Array
Javascript Array Concat: Adding One Array To Another
Javascript Join: Joining Elements of an Array

A Note On Browser Compatibility



Arrays were an add-on afterthought to javascript; for that reason you can find various ways of using them listed on programming websites, including references to an Array object.

The 'Array' object is however basically obsolete now; in this tutorial we'll look at current best practices.

The code below won't work on very old browsers; however, javascript has been stable enough for long enough now that I suggest disregarding any browsers too old to run the following code. Your user base is unlikely to be affected much. Those who are using browsers too old to run such basic javascript, really need to upgrade their browsers.

Creating and Initializing Arrays In Javascript



You can create an array in javascript as follows (in this example you can see an entire .html file; later on we'll just look at the javascript part):

<html>

<head>
<title>Basic Javascript Array Example</title>

<script language="javascript">
// Empty array
var empty = [];

// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi'];

alert(fruits[1]);
</script>
</head>

<body>

</body>

</html>






To add elements to an array in javascript, just define a new element at the end of the array.

You can also use push() to 'push' a new element onto the end of the array, or unshift() to add elements to the start of an array:


// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi'];

// Adding new elements to the end of
// the array:
fruits[3] = 'banana';
fruits[4] = 'pear';

// Or you can just do this ...
fruits[fruits.length] = 'pineapple';
fruits[fruits.length] = 'cherry';

// Or this:
fruits.push('grape');
fruits.push('raspberry');

// Or you can add elements to the START
// of the array like this:
fruits.unshift('raspberry');
fruits.unshift('blackberry');




Multidimensional Arrays in Javascript



You can also create multidimensional arrays. The sub-arrays do not have to be all the same length.

var stuff = [
    [1, 2, 3],
    ['one', 'two', 'three'],
    ['apple', 'orange', 'banana', 'kiwi']
];

alert(stuff[2][1]);






Iterating Through Arrays in Javascript



You can iterate through an array in javascript using a for loop with a counter that runs from zero to one less than the length of the array.

Here we create an array called 'fruits'; we then pass the array to a function that iterates through the array and writes the array members to the HTML document body, one per line:


function show_array(array) {
    for(var i=0; i<array.length; i++) {
        document.write(array[i]);
        document.write('<br/>');
    }
}

var fruits = ['apple', 'orange', 'banana'];

show_array(fruits);




apple
orange
banana




You can also use for in a 'for each' kind of a way, meaning that we could have chosen to write the above function, showarray() as follows (here I've also modified showarray() so that it shows the array contents in an alert box rather than writing to the document):

function show_array(array) {

    var text = '';
    
    for(var i in array) {
        text += array[i];
        text += 'n';
    }
    
    alert(text);
}






Note that i is still the item index, not the item itself.

For genuine 'for each'-type loops in javascript, you can use one of the several popular javascript libraries; for instance, jQuery defines an 'each' iterator that gets you the elements of an array one by one.

Javascript Array Sort: Sorting Arrays in Javascript



To sort an array in javascript, use the sort() function. You can only use sort() by itself to sort arrays in ascending alphabetical order; if you try to apply it to an array of numbers, they will get sorted alphabetically.

var fruits = ['apple', 'orange', 'banana'];
var numbers = [10, 20, 2, 3, 0, 500];

// This works.
fruits.sort();

// This sorts alphabetically, not numerically!
numbers.sort();

// We defined show array earlier.
show_array(fruits);
show_array(numbers);




Strings are sorted alphabetically:



But so are numbers:




To sort numbers, or to sort strings non-alphabetically, or to sort an array containing something else altogether, you must supply your own sort algorithm. This is done by passing the name of a function containing a sort algorithm to sort(). You can also just define the sort algorithm function 'inline', as in the following example.

The sort algorithm function receives two arguments; these are array elements that must be compared. If the first element is bigger than the second (in other words, comes later in the sort order), return 1. If the first element is smaller than the second (comes earlier in the sort order), return -1. If the elements are equal, return 0.

var fruits = ['apple', 'orange', 'banana'];
var numbers = [10, 20, 2, 3, 0, 500];

// Sort in reverse alphabetical order.
fruits.sort(function(a, b) {
    if(a > b) {
        return -1;
    }
    else if(a < b) {
        return 1;
    }
    else {
        return 0;
    }
});

// Sort in ascending numerical order.
numbers.sort(function(a, b) {
    if(a > b) {
        return 1;
    }
    else if(a < b) {
        return -1;
    }
    else {
        return 0;
    }
});

// We defined show array earlier.
show_array(fruits);
show_array(numbers);




The fruits array is now sorted in reverse alphabetical order:




The numbers array is sorted numerically:



Pop and Shift: Removing Elements From Arrays in Javascript



You can remove elements from the end of an array in javascript using pop() and from the start of an array using shift(). Both of these functions return the removed elements.

// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi'];

alert(fruits.pop());
alert(fruits.shift());














Javascript Slice: Selecting Part of an Array



You can obtain an array consisting of part of another array in javascript using slice(START, END).

START is the index of the first item to include in your selection. END is the index of item after the last one you want to include. In other words, END is not included in your selection.

Here's an example (note that the slice() method does not change the array you are slicing from):

// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi', 'banana'];

var juice = fruits.slice(1, 3);

show_array(juice);






If you don't include an END index, slice() gives you all elements up to the end of the array.

// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi', 'banana'];

var juice = fruits.slice(1);

show_array(juice);






... and you can specify element from the end of the array instead of the beginning by supplying a negative index to slice():


// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi', 'banana'];

// Slice off the last two elements.
// (the fruits array will not be changed)
var juice = fruits.slice(-2);

show_array(juice);






Javascript Array Concat: Adding One Array To Another



You can combine two arrays in javascript using the concat() method. Note that the original array is unchanged; concat() returns a new array containing elements of the combined arrays.

// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi'];

var more = ['cherry', 'pear'];

var all = fruits.concat(more);

show_array(all);






Javascript Join: Joining Elements of an Array



You can join together the elements of an array using join(), which returns a string containing the joined array elements.

This is very handy for displaying arrays using alert (although modern browsers will generally display the array elements anyway if alert is supplied directly with the name of the array).

If called with no argument, join() defaults to joining the array elements with a comma. If an argument is supplied, that string is used to join the array elements. In the following example, we join the elements of the fruit array using a comma and space.

// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi'];

var text = fruits.join(', ');

alert(text);









If you can think of anything I've missed or you have further questions (or you spot a mistake!), feel free to leave a comment.