Friday, July 11, 2014

07 - Arrays


Array Construction
Arrays can be created by invoking the constructor Array:
 
var array1 = new Array();
array1[0] = "a";
array1[1] = 1;
array1[2] = true;

console.log(array1); // ["a", 1, true]
 
Notice that elements in an array are not necessary to have the same type. Three elements in array1 in the code above are a string, number, Boolean value correspondingly.
 
There is also a more concise way to construct an array, as shown below:
 
var array2 = ["a", 1, true];

console.log(array2); // ["a", 1, true]
 
Elements are surrounded by a pair of square brackets during the array construction.
 
Iterating Array Elements
Some elements inside an array may be undefined. When an array with some undefined elements is traversed with different strategies, the results might be different. Let's take the following piece of code as an example:
 
var array = [0, 1];
array[4] = 4;

console.log("length:", array.length); // length: 5
for(var index = 0; index < array.length; ++index) {
    console.log(index + ":", array[index]);
}

// Output:
// 0: 0
// 1: 1
// 2: undefined
// 3: undefined
// 4: 4

for(index in array) {
    console.log(index + ":", array[index]);
}

// Output:
// 0: 0
// 1: 1
// 4: 4
// name: linear increasing

array.forEach(function(value, index) {
    console.log(index + ":", value);
});

// Output:
// 0: 0
// 1: 1
// 4: 4
 
Firstly, an array is initialized with two numbers 0 and 1. The element with index 4 is set as 4. Now array has 5 elements, but the two elements with index 2 and 3 are undefined yet. When the array is traversed in the first for loop, both defined and undefined elements are listed. However, when the array is traversed in the for…in loop, only defined elements are listed.

The difference between the for...in loop and the method forEach is that for...in loop also iterates the property of the array, but the forEach does not. A property name is added into the array, and it is printed out when the array is iterated with for...in loop, but not with the forEach method.
 
Basic Array Functionalities
There are many predefined array methods, which fulfill basic array functionalities. The code below shows some most frequently used methods:
 
var array1 = [1, 2];
var array2 = [4, 3, 2];
var array3 = [5, 6];

var array4 = array1.concat(array2, array3);
console.log(array4); // [1, 2, 4, 3, 2, 5, 6] 

var index1 = array4.indexOf(2);      
var index2 = array4.lastIndexOf(2);  
console.log(index1); // 1
console.log(index2); // 4

var str = array4.join("; ");
console.log(str); // 1; 2; 4; 3; 2; 5; 6

var array5 = array4.slice(2, 5);
console.log(array5); // [4, 3, 2]

array4.sort();
console.log(array4); // [1, 2, 2, 3, 4, 5, 6]
 
The method concat concatenates two array into a longer one. The methods indexOf and lastIndexOf get the first and last index of the given element out of an array respectively. The method join convert an array into a string with the given delimiter between elements. The method slice gets a substring out of a string. As the name suggests, the method sort is used to sort an array.
 
Sort
Sometimes the result of the method sort is surprising. The following is an example
 
var array = [4, 20, 10, 7];
array.sort();
console.log(array); // [10,20,4,7]
 
After the array with numbers 4, 20, 10, and 7 gets sorted, the result is unexpected. That is because the default criteria to sort in alphabetical order. If the desired behavior is to sort based in numeric order, we have to define our own callback function to compare elements in the array:
 
var array = [4, 20, 10, 7];

function compare(a, b) {
    return a - b;
}

array.sort(compare);
console.log(array); // 4,7, 10, 20
 
Arrays as Stacks
Stacks are not defined explicitly in JavaScript. Fortunately, arrays can be used as stacks, because the methods push and pop are defined on arrays:
 
var array = [1, 2];

array.push(3); // [1, 2, 3] 
console.log(array);

array.push(4); // [1, 2, 3, 4]
console.log(array);

console.log(array.pop()); // 4
console.log(array.pop()); // 3
console.log(array); // [1, 2] 
 
As expected, the method push appends an element into the end of an array, and the method pop removes the last element of an array.
 
Similarly, there are two more methods to manage elements at the beginning of an array. The method unshift inserts at the beginning of an array, and the method shift deletes the first element:
 
var array = [1, 2];

array.unshift(3);
console.log(array); // [3, 1, 2]

array.unshift(4);
console.log(array); // [4, 3, 1, 2]

console.log(array.shift()); // 4
console.log(array.shift()); // 3
console.log(array); // [1, 2]
 
Arrays as Queues
If we always insert elements into an array with the method push, and delete elements with the method shift, elements are in the first in first out order, as demonstrated below:
 
var queue = [1, 2];

queue.push(3); // [1, 2, 3] 
console.log(queue);

queue.push(4); // [1, 2, 3, 4]
console.log(queue);

console.log(queue.shift()); // 1
console.log(queue.shift()); // 2
console.log(queue); // [3, 4] 
 
Delete, Replace, and Insert Elements
 
There is a more powerful method to insert, delete, and to replace elements at any places inside an array, which is named as splice. Where there only two parameters are passed into the method splice, the method is used to delete elements from an array:
 
var array1 = [1, 2, 3, 4, 5, 6, 7];
array1.splice(3, 2);
console.log(array1); // [1, 2, 3, 6, 7]

var array2 = [1, 2, 3, 4, 5, 6, 7];
array2.splice(-3, 2);
console.log(array2); // [1, 2, 3, 4, 7]
 
The first parameter stands for the starting index of elements to be deleted. If it is a negative number, the index starts from the right side of an array. For example, the starting index 3 in the array [1, 2, 3, 4, 5, 6, 7] is in value 4, and the starting index -3 in the array is in 5.
 
The second parameter is for the number of elements to be deleted. When two elements starting from the index 3 are delete from the array [1, 2, 3, 4, 5, 6, 7], it becomes [1, 2, 3, 6, 7]. And it becomes [1, 2, 3, 4, 7] when two elements are deleted starting from the index -3.
 
If there are more than two parameters are passed into the method splice, it is used two replace elements. For instance:
 
var array1 = [1, 2, 3, 4, 5];
array1.splice(2, 2, -1);
console.log(array1); // [1, 2, -1, 5]

var array2 = [1, 2, 3, 4, 5];
array2.splice(2, 2, -1, -2);
console.log(array2); // [1, 2, -1, -2, 5]

var array3 = [1, 2, 3, 4, 5];
array3.splice(2, 2, -1, -2, -3);
console.log(array3); // [1, 2, -1, -2, -3, 5]
 
In the code above, two elements starting from the index 2 (elements with value 3 and 4) are replaced with elements in the parameter list starting from the index 2 (negative parameters in the examples above).
 
If we are going to insert elements into an array, the second parameter of the method splice should be 0. The following is an example to insert elements:
 
var array = [1, 2, 3, 4, 5];
array.splice(2, 0, -1, -2);
console.log(array); // [1, 2, -1, -2, 3, 4, 5] 
 
In the code above, two negative numbers -1 and -2 are inserted into the array [1, 2, 3, 4, 5], starting from the index 2.
 

No comments :

Post a Comment