Chapter 3 Array

Node.js provides an Array object for collection manipulation. In general, a Node.js Array object has the same behavior with a JavaScript Array object. In this section, we are going to manipulate an Array object in Node.js

Creating an Array Object

There are three ways to create an Array object. The first is simply by typing the array object.

var array = [];

Option two is to create an Array object by instantiating the Array object.

var array = new Array();

The last option is to create an Array object by inserting collection data.

var array = [3,5,12,8,7];

Inserting Data

After creating an Array object, we can insert data. Use [] with index if you want to assign the value.

array[0] = 3;
array[1] = 5;
array[2] = 12;
array[3] = 8;
array[4] = 7;

You can also use the push() function to insert data.

array.push(10);
array.push(18);

Accessing Data

To access array data, you can use [] with data index parameter.

// show data
console.log(array);
for(var i=0;i<array.length;i++){
    console.log(array[i]);
}

Figure 1: Showing array data

Updating Data

To update an item of array data, you can use [] with data index and thus assign a new value.

// edit
array[2] = -2;
array[3] = 5;
console.log(array);

Removing Data

You can use the pop() function to remove data from the Array. If you want to remove data by specific index then you can use the splice()function.

The following is a sample script for removing data:

// remove data
array.pop();
array.pop();
    
// remove data by index
var index = 1;
array.splice(index,1);
console.log(array);