CHAPTER 3
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
There are three ways to create an Array object. The following is how to create an Array object.
var array = []; |
Option 2, we can create an Array object by instantiating Array object.
var array = new Array(); |
The last option, creating Array object is by inserting collection data.
var array = [3,5,12,8,7]; |
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); |
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 19: Showing array 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); |
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); |