top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Arrays in javascript

0 votes
294 views

Arrays

An array is a collection of values stored in adjacent memory locations. These array values are referenced using a common array name.

Consider a scenario where you want to store the names of 100 employees within an IT department. This can be done by creating 100 variables and storing the names. But keeping track of 100 variables is a tedious task and it results in inefficient memory utilization. The solution to this problem is to create an array variable to store the names of 100 employees.

Single-dimensional Arrays

The values of an array variable must be of the same data type. These values that are also referred as elements can be accessed by using subscript or index numbers. The subscript number determines the position of an element in an array list. In a single-dimensional array, the elements are stored in a single row in the allocated memory. In JavaScript, the first array element has the index number zero and the last array element has an index number one less than the total number of elements. This arrangement helps in efficient storage of data. In addition, you can easily sort data and track the data length.

Declaring Arrays
Arrays in JavaScript can be created in two different ways. First, you can create an array variable by using the array object and new keyword. This declaration can also specify the size of the array element. When an array is created by specifying the size, memory is allocated to the array variable.

After the creation of an array, you can initialize the individual array elements by assigning values to them. You can also initialize the array elements at the time of declaration. This is done by specifying the values in square brackets separated by commas. The other method is creating an array without using the new keyword and initializing it at the time of declaration.

The Syntax demonstrates how to create a single-dimensional array.

Var variable_name = new Array(size); //Declaration

Variable_name[index]= ‘value’;

Where,

             Variable_name: Is the name of the variable.

             Size: Is the number of elements to be declared in the array.

             Index: Is the index position.

 

Multi-dimensional array

A multi-dimensional array stores a combination of values of a single type in two or more dimensions. These dimensions are represented as rows and columns similar to those of a Microsoft Excel Sheet. A two-dimensional array is an example of the multi-dimensional array.

JavaScript does not directly support two-dimensional array. You can create two-dimensional array by creating an array of arrays. To create a two-dimensional array, you first declare an array and then create another an array to each element of the main array. This means that you have created array to each array element.

Var students = new Array(3);  //declaration

Students[0]= new Array(‘john’,’65’);

Students[1]= new Array(‘David’,’78’);

Students[2]= new Array(‘Richard’,’57’);

The syntax demonstrates how to declare a two-dimensional array.

Var variable_name = new Array(size);  //Declaration

Variable_name[index] = new Array(‘value1’,’value2’..);

//Initialization

Where,

Variable_name: Is the name of the array.

Index: Is the index position.

Value1: Is the value at the first column.

Value2: Is the value at the second column.

 

Array Methods

An array is a set of values grouped together and identified by a single name. In JavaScript, the array object allows you to create arrays. It provides the length property that allows you to determine the number of elements in an array. The various methods of the array object allow you to access and manipulate the array elements. The table lists the most commonly used methods of the array object.

Method

Description

Concat

Combine one or more array variables

Join

Joins all the array elements into a string.

Pop

Retrieves the last element of an array.

Push

Appends one or more elements to the end of an array.

Sort

Sorts the array elements in an alphabetical order.

 

Example

Consider a scenario where you want to create an array to display a list of flowers. In addition, you want to access and manipulate the different elements of an array. To access and manipulate the array elements:

1. An array variable, flowers, is created that stores the names of three flowers.

2. The length property is used to display the number of flowers in the array variable.

3. The join() method joins the flower names and separates them with a comma.

4. The push() method adds orchid and lily at the end of the array and the total number of flowers in the array list is displayed as 5.

5. The sort() method sorts the flowers in alphabetical order.

6. The pop() method retrieves the last element that is sunflower, from the array list.

Go through this tutorial video:

References

Learning JavaScript by Shelley Powers
posted Jun 9, 2017 by Raju Raj

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

An array which can have arrays as its element are called multi-dimensional array. Or in simple words if array has more then one subscript then it is called multi-dimensional array.

Declaration
type arrayName [SubscriptSize1 ][SuscriptSize2]...[SubscriptSizeN];

Examples

char arr[5][10];
char arr[50][5][10];

In example 1 arr means 5 rows and 10 columns. Since its a char array so each row can contain a string of max 10 characters and total 5 such strings are possible.
In example 2 arr means 50 arrays of example 1.

Multi-dimensional Array Visualization

Multi-Dimensional Array

Once we visulize the array in the following manner nothing is complex see the following figure which is a representation of array[3][4][5].

Memory Representation

Though in the above example we have seen the array in the matrix form or matrix of matrix form but in reality they are stored in the contiguous fashion in the memory.

a[0][3] = a[0][0] + Size of Data Type

Example:
Assume that we have an array a as a[3][3] and the base address i.e. a[0][0] is 1000, and size of data type is say 2. Then it will have following address in the memory -

a[0][0] = 1000
a[0][4] = 1002
a[0][2] = 1004
a[1][0] = 1006
a[1][5] = 1008
a[1][2] = 1010
a[2][0] = 1012
a[2][6] = 1014
a[2][2] = 1016

Note: Remember that all the leaf element/variable of an multi-dimentional array should/would be of same type.

READ MORE

An array is a collection of same type of elements which are sheltered under a common name.

Instead of declaring individual variables, such as elem0, elem1, ...one can declare one array variable such as elem and use elem[0], elem[1], ...to represent individual variables. A specific element in an array is accessed by an index.

Example

+===================================================+
| elem[0]    |  elem[1]    | elem[2]    | elem[3]   |
+===================================================+

Defining an Array

type arrayName [ arraySize ]; //single-dimensional array declaration 

<type> can be any valid C data type.
<arraySize> must be an integer constant greater than zero

Initializing an Array

Example: Integer Array - Individual Initialization

int a[5];
int i = 0;
for(i=0;i<sizeof(a);i++) 
{ 
  a[i] = i; 
} 

Example: Integer Array - Initializing array at the time of declaration.

int a[] = {1,2,3,4,5};

Example: String Initialization

char s[] = "Hello";
or 
char s[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Identical to the previous one 

Example: Array of Pointers

int main()
{
    char *ptr1 = "Pradeep";
    char *ptr2 = "Kohli";
    char *ptr3 = "India"; 

    //Declaring an array of 3 char pointers
    char* a[3]; 

    // Initializing the array with values
    a[0] = ptr1;
    a[1] = ptr2;
    a[2] = ptr3; 
}

Example: Pointer to an Array

type (*arrayName)[arraySize]

For example :

int(*p)[5];

Difference between a pointer and an array

All the above example can give a mislead about an array and can feel also like a pointer. But here are few points which differentiates the pointer with an array -

  1. A pointer is a place in memory that keeps address of another place inside where as an array is a single, pre allocated chunk of contiguous elements (all of the same type), fixed in size and location.
  2. Pointer can’t be initialized at definition (it first need to be allocated). Array can be initialized at definition.

    int num[] = { 1, 2, 3};

  3. Pointer is dynamic in nature. The memory allocation can be resized or freed later. where as arrays are static in nature. Once memory is allocated , it cannot be resized or freed dynamically.
  4. Array name is constant while pointer name is variable.
READ MORE
...