Thursday, 13 August 2015

InDetail: Arrays In JavaScript

what's an Array?

In General:
    An Array is a contiguous data structure, that stores multiple values. The values stored inside of an array are called as array elements. You can access elements of an array through indexes. It is an index based. The index starts from 0. That is, first element has index as 0 and index of 2nd element is 1 and so on.

As per ECMAScript:
ECMA script is standardized scripting language, JavaScript is it's implementation. As per ECMA

1. Arrays are maps i.e mapping of index to value.
2. They are not contiguous, they can have holes in them, i.e you can have an array in which you can have values for index 0, 2, 4, even though index 1, 3 have no values.

Most JavaScript engines optimize array without holes internally and store them contiguously. An array looks like below.


Now, let's see how to create an array, access elements inside it and some other details in detail.

Creating An Array in JavaScript:

You can create an array in two ways i.e using array literal, using array constructor.

1. Using Array Literal:

Here i am going to create a String array using array literal syntax.
var arr = ["a","b","c"];
Now variable "arr" contains 3 String elements in it.

Any trailing commas inside the square brackets are ignored. for example,
var arr = ['a','b',];
the above declaration doesn't throw any error. It just ignores the extra comma(",") at the end. The array contains only two String elements i.e a, b.

2. Using Array Constructor (Array()):

You can also create an array using the Array constructor. Let's see some examples below.

Creating an empty Array :
var arr = new Array();
Here, variable arr is just an empty array.

Creating an empty Array with specified length:
var arr = new Array(2);
here variable arr just contains 2 empty slots. Some JavaScript engines may preallocate continuous memory when you use Array() constructor, which may slightly improves performance, but the code looks verbose and redundant.

Creating an Array with elements:

You can pass elements to the array constructor, so that the array stores the given values. for example.
var arr = new Array("a","b","c");
Here, variable arr has 3 strings in it.

The problem with this approach is you can't create an array with single numeric value in it. for example,
var x = new Array(2); Here it creates an empty array of size 2, but our intention is to create an array with value 2 in it.
var x = new Array(2.5); // throws an error,

var x = new Array('x'); // ok, no errors.

Adding Values to Array:

Using Array Index: 

you can add values to the array, using it's index just like below.
var arr = [];

arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = "3";
Here, we are adding elements to the array using indexes i.e 0, 1, 2 and so on. 






Using push():

 As arrays are objects in JavaScript, you can use it's push() function to add values. The push() function adds the element at the end of the array. for example.
var arr = [];

arr.push(1); // adds element at the end, i.e at index 0

arr.push(2); // adds element at index 1.

Accessing Array Elements:

Just like how you inserted values to the array using indexes, you can also access elements using indexes only. An array index starts from 0 to length - 1. length is length of the array.

The length of the array can be find using it's length property. i.e "arr.length". Let's see a simple example of accessing array element.
var arr = [1,2,3];

console.log(arr[0]); // prints 1 to the console.

console.log(arr[1]); // prints 2 to the console. 

console.log(arr[2]); // prints 3 to the console.

How to check whether an array has element at given index:

You can use in operator for this purpose. Just like other operators it takes two operands, Left operand is the index and right operand is the array.  for example
var arr = ['a','b','c'];


0 in arr; //gives true

1 in arr; // returns true

2 in arr; // returns true

3 in arr; // returns false.

4 in arr; // returns false.

Deleting Array Elements:

You can delete an element from array using delete operator. Deleting an element from array won't resize the array, it just creates a hole inside the array. The length property of array also remains same. for example.

In the above image, you can see deleting array element 2, doesn't resize the array.

Deleting Trailing Elements From Array:

Deleting trailing element is not different from deleting any array element. There are 2 ways, one is using delete operator just like above, the other is,

If you decrease length of the array, it removes any trailing elements. For example, if you want to delete last 2 elements from array, just decrement 2 from array length property.
var arr = [1,2,3,4,5,6];

arr.length -= 2; // removes 5,6 and resizes array.

Deleting Elements Without Creating Holes in Array:

use splice() function for this purpose. For example, if you want to remove an element from position 1, you need to pass 2 arguments to splice() method i.e at which position, how many elements.
splice(pos,noEles);

if you want to remove 2 elements from a 0th position, you can use arr.splice(0,2). The following script shows various uses of splice().
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']

Multidimensional Arrays:

1. Creating multidimensional arrays in JavaScript is not similar to other languages such as C, C++, Java.

2. In C, C++, Java, you can create a multidimensional array like this

int arr[][];

3. But in JavaScript, you must nest arrays for this purpose. for multidimensional arrays first create an outer array and then insert new arrays into it, just like below.
var arr = []; // an empty outer array.

arr[0] = []; arr[1] = []; arr[2] = []; // inserted 3 empty arrays into outer array.

4. Once you created nested array, you can access inner arrays just like accessing elements of an array with index and you can insert values into those. just like below.
arr[0][0] = 5; // inserted 1st element into first inner array.

arr[0][1] = 6; // inserted 2nd element into first inner array.

arr[0][2] = 7; // inserted 3rd element into first inner array.

Some Useful Functions of Arrays: 
Array.isArray(obj) true if object is an array, false if it is not
Array.of(ele1,...) Creates a new Array instance with variable number of arguments
join() joins all elements of an array into a string
indexOf() returns the first index at which a given element found, -1 if it is not present
pop() removes last element and returns that element
push(ele1,ele2,...) adds one or more elements to the array and returns length of the array
reverse() reverses an array in place
sort() sorts the elements of array inplace and returns the array
shift() removes first element from the array and returns that element
toString() returns string representation of array

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.