JavaScript Arrays
Displaying Arrays
In this tutorial we will use a script to display arrays inside a <p> element with id="demo":
Example
<p id="demo"></p>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
The first line (in the script) creates an array named cars.
The second line "finds" the element with id="demo", and "displays" the array in the "innerHTML" of it.
Example
var cars = ["Saab", "Volvo", "BMW"];
var cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
var cars = [
"Saab",
"Volvo",
"BMW"
];
Never put a comma after the last element (like "BMW",). The effect is inconsistent across browsers.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
var car2 = "Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Example:
var cars = ["Saab", "Volvo", "BMW"];
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).
For simplicity, readability and execution speed, use the first one (the array literal method).
Access the Elements of an Array
You refer to an array element by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
[0] is the first element in an array. [1] is the second. Array indexes start with 0.
You Can Have Different Objects in One Array
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
myArray[1] = myFunction;
myArray[2] = myCars;
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
Examples
var x = cars.length; // The length property returns the number of elements in cars
var y = cars.sort(); // The sort() method sort cars in alphabetical order
Array methods are covered in the next chapter.
The length Property
The length property of an array returns the length of an array (the number of array elements).
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
The length property is always one more than the highest array index.
Adding Array Elements
The easiest way to add a new element to an array is using the push method:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
Adding elements with high indexes can create undefined "holes" in an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[10] = "Lemon"; // adds a new element (Lemon) to fruits
Looping Array Elements
The best way to loop through an array, is using a "for" loop:
Example
var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
}
Associative Arrays?
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
Example:
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"
WARNING !!
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
The Difference Between Arrays and Objects?
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
Arrays are a special kind of objects, with numbered indexes.
When to Use Arrays? When to use Objects?
JavaScript does not support associative arrays.
You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.
Avoid new Array()
There is no need to use the JavaScript's built-in array constructor new Array().
Use [] instead.
These two different statements both create a new empty array named points:
var points = new Array(); // Bad
var points = []; // Good
var points = []; // Good
These two different statements both create a new array containing 6 numbers:
var points = new Array(40, 100, 1, 5, 25, 10) // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword complicates your code and produces nasty side effects:
var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
What if I remove one of the elements?
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!
How to Recognize an Array?
A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
var fruits = ["Banana", "Orange", "Apple", "Mango"];
typeof fruits; // typeof returns object
The typeof operator returns object because a JavaScript array is an object.
To solve this problem you can create your own isArray() function:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
return myArray.constructor.toString().indexOf("Array") > -1;
}
The function above always return true if the argument is an array.
Or more precisely: it returns true if the object prototype of the argument is "[object array]".
JavaScript Array Methods
The strength of JavaScript arrays lies in the array methods.
Converting Arrays to Strings
In JavaScript, all objects have the valueOf() and toString() methods.
The valueOf() method is the default behavior for an array. It returns an array as a string:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.valueOf();
document.getElementById("demo").innerHTML = fruits.valueOf();
For JavaScript arrays, valueOf() and toString() are equal.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
document.getElementById("demo").innerHTML = fruits.toString();
The join() method also joins all array elements into a string.
It behaves just like toString(), but you can specify the separator:
Example
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
<script>
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is: Popping items out of an array, or pushing items into an array.
The pop() method removes the last element from an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
fruits.pop(); // Removes the last element ("Mango") from fruits
The push() method adds a new element to an array (at the end):
Remember: [0] is the first element in an array. [1] is the second. Array indexes start with 0. |
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
The pop() method returns the string that was "popped out".
The push() method returns the new array length.
Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.
The shift() method removes the first element of an array, and "shifts" all other elements one place down.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
fruits.shift(); // Removes the first element "Banana" from fruits
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
The shift() method returns the string that was "shifted out".
The unshift() method returns the new array length.
Changing Elements
Array elements are accessed using their index number:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi"
fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi"
The length property provides an easy way to append a new element to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
delete fruits[0]; // Changes the first element in fruits to undefined
Using delete on array elements leaves undefined holes in the array. Use pop() or splice() instead. |
Splicing an Array
The splice() method can be used to add new items to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits
fruits.splice(0, 1); // Removes the first element of fruits
The first parameter (0) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
Sorting an Array
The sort() method sorts an array alphabetically:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
fruits.sort(); // Sorts the elements of fruits
Reversing an Array
The reverse() method reverses the elements in an array.
You can use it to sort an array in descending order:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
fruits.reverse(); // Reverses the order of the elements
fruits.sort(); // Sorts the elements of fruits
fruits.reverse(); // Reverses the order of the elements
Numeric Sort
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
You can fix this by providing a compare function:
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
points.sort(function(a, b){return a-b});
Use the same trick to sort an array descending:
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
points.sort(function(a, b){return b-a});
The Compare Function
The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments:
function(a, b){return a-b}
When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
Example:
When comparing 40 and 100, the sort() method calls the compare function(40,100).
The function calculates 40-100, and returns -60 (a negative value).
The sort function will sort 40 as a value lower than 100.
Find the Highest (or Lowest) Value
How to find the highest value in an array?
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
// now points[0] contains the highest value
points.sort(function(a, b){return b-a});
// now points[0] contains the highest value
And the lowest:
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
// now points[0] contains the lowest value
points.sort(function(a, b){return a-b});
// now points[0] contains the lowest value
Joining Arrays
The concat() method creates a new array by concatenating two arrays:
Example
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys
The concat() method can take any number of array arguments:
Example
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias","Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
var arr2 = ["Emil", "Tobias","Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
Slicing an Array
The slice() method slices out a piece of an array into a new array:
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
var citrus = fruits.slice(1, 3);
The slice() method selects elements starting at the start argument, and ends at, but does not include, the end argument.
If the end argument is omitted, the slice() method slices out the rest of the array:
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
var citrus = fruits.slice(1);
Comments
Post a Comment