Most Node.js programs use arrays. An array stores one element after another—it is a linear collection of elements, and it can keep expanding.
We initialize with square brackets, and we call the push()
method to add. Modern JavaScript runtimes (like Node) optimize operations on arrays.
Here we see an array literal with 3 elements—we initialize it with the values 10, 20 and 30. It begins existence with a length of 3.
string
representation of the array to console.log
.var numbers = [10, 20, 30]; // Part 1: print the array elements. console.log("ARRAY: " + numbers); // Part 2: get length of array. var length = numbers.length; console.log("LENGTH: " + length);ARRAY: 10,20,30 LENGTH: 3
This function appends an element to the end of an array. It is an "add" or "append" function. The original array is modified, so we would need to copy the original to retain it.
// Create an empty array. var numbers = []; // Add two elements to the array with push calls. numbers.push(0); numbers.push(10); console.log("PUSH RESULT: " + numbers);PUSH RESULT: 0,10
It is possible to create an array with an initial size. This can prevent an array from needing to be resized during use. An initial size can improve performance.
// Use new Array with one integer to have undefined elements. var result = new Array(5); console.log("ARRAY: " + result);ARRAY: ,,,,
This function removes the last element from an array and returns it. With push()
and pop()
we use an array like a stack. We can ignore the return value if we do not need it.
Pop()
removes the last element, so it leaves no gap in the array. No elements need to be shifted forward after a pop()
.var colors = ["red", "blue", "green"]; // Remove last element from the array. var removed = colors.pop(); console.log("COLORS: " + colors); console.log("REMOVED: " + removed);COLORS: red,blue REMOVED: green
IndexOf
We search arrays with the indexOf()
method. If an element matches, its index is returned. If nothing is found, the special value -1 is returned.
var codes = [100, 200, 300, 999]; // This is located at index 1. var result200 = codes.indexOf(200); console.log("RESULT FOR 200: " + result200); // Not in the array so -1 is returned. var result7 = codes.indexOf(7); console.log("RESULT FOR 7: " + result7);RESULT FOR 200: 1 RESULT FOR 7: -1
LastIndexOf
With this function we search an array from its end. Other than the search direction and starting point, it is the same as indexOf
.
lastIndexOf
—its index is 2, meaning the third element.var colors = ["blue", "blue", "blue"]; // Find last occurring "blue" color. var lastBlue = colors.lastIndexOf("blue"); // Print the index we found. console.log("LAST BLUE: " + lastBlue);LAST BLUE: 2
For
-loopHere is the JavaScript for
-loop on an array. We access all the indexes of the array. The highest index is one less than the length of the array.
var letters = ["x", "y", "z"]; // Loop over indexes with for-loop. for (var i = 0; i < letters.length; i++) { console.log("FOR: " + letters[i]); }FOR: x FOR: y FOR: z
For
-in loopWith a for-in
loop we can access all the indexes of an array without specifying the start or end indexes. This is a simpler way to loop over array elements.
for-in
loop on an array, we must still access the element with an index. The iteration variable is an index.for-in
loop. So this loop is probably not the best one for arrays.var letters = ["g", "h", "i"]; // Loop over indexes with for-in loop. for (var i in letters) { console.log("FOR IN: " + letters[i]); }FOR IN: g FOR IN: h FOR IN: i
For
-of loopThis loop returns all the elements in the array. No indexes are returned—just elements. This is a way to enumerate all the elements in an array with clear code.
var sides = ["left", "center", "right"]; // Loop over elements with for-of. for (var side of sides) { console.log("FOR OF: " + side); }FOR OF: left FOR OF: center FOR OF: right
This method takes part of an array. It accepts 2 arguments: the first is the start index of the slice, and the second is the last index (not an element count).
var codes = [10, 20, 30, 0, -1]; // Slice receives a first index, and a last index. // ... It returns the elements in that range. var slice1 = codes.slice(1, 2); var slice2 = codes.slice(1, 3); console.log("SLICE 1: " + slice1); console.log("SLICE 2: " + slice2);SLICE 1: 20 SLICE 2: 20,30
This method removes elements and adds new ones in their place. It both removes and inserts in a single method call. It receives multiple arguments.
var codes = [10, 20, 30, 40]; // First argument is the index we start at. // ... Second argument is the number of elements we remove. // ... Then we add the following arguments. codes.splice(1, 2, 900, 1000, 1100); console.log("SPLICE: " + codes);SPLICE: 10,900,1000,1100,40
Reverse
This method inverts the ordering of an array. Reverse()
modifies the existing array and does not create a copy. So we must copy the original to keep it around.
var colors = ["blue", "red"] // Reverse the ordering of the array. // ... The original is modified. var reversed = colors.reverse(); console.log("REVERSED: " + colors);REVERSED: red,blue
Here we loop over two elements at a time, accessing the left and right element. We start at index 1 to avoid accessing an element at index -1.
var codes = [10, 20, 25, 35]; // Loop over adjacent elements (pairs) in the array. for (var i = 1; i < codes.length; i += 2) { // Write left and right elements. var left = codes[i - 1]; var right = codes[i]; console.log("LEFT: " + left); console.log(" RIGHT: " + right); }LEFT: 10 RIGHT: 20 LEFT: 25 RIGHT: 35
In optimized JavaScript compilers, an array can be sparse. When an array has just a few assigned elements, it is more efficient to just store those elements.
// Create an array. var results = []; // Only two elements are assigned in this sparse array. results[99999] = 5; results[1] = 0; console.log("SPARSE LENGTH: " + results.length); console.log("SPARSE LAST: " + results[99999]);SPARSE LENGTH: 100000 SPARSE LAST: 5
This method removes and returns the first element of an array. The following elements are shifted forward so that the second element becomes the first element.
var gems = ["ruby", "sapphire", "crystal"]; console.log("BEFORE: " + gems); // Shift returns the first element in the array. // ... It also removes that element from the array. var shifted = gems.shift(); console.log("SHIFTED: " + shifted);BEFORE: ruby,sapphire,crystal SHIFTED: ruby
ToString
This method converts an array into a string
. Each element is separated by a comma. We see that an array of 3 elements is converted to a string
with a length of 20 characters.
string
. So if a string
contains a comma, it may be impossible to convert this string
back into an array.string
format that can be reused with no data loss, consider JSON.stringify
.var words = ["note", "tip", "information"]; // Convert array to string. var result = words.toString(); // Write result and length. console.log("STRING: " + result); console.log("LENGTH: " + result.length);STRING: note,tip,information LENGTH: 20
Join
With this method we combine elements from an array into a string
. We specify the separator string
(which can be zero or more characters).
Join
is the opposite of split. If the delimiter is not found in any of the strings, we can use split()
to reverse a join.var vehicles = ["car", "train", "plane", "boat"]; // Join with a delimiter character. var result = vehicles.join("/"); console.log("JOINED: " + result);JOINED: car/train/plane/boat
ForEach
functionLooping over the elements in an array can be done with the forEach()
function. We must provide a function argument that handles each element.
forEach()
on an array, and call the handleElement
function on each individual element.forEach()
instead of a for
-loop can reduce errors and lead to more elegant code.function handleElement(x) { // This is called on each element in the array. console.log("FOREACH: " + x) console.log("FOREACH TIMES 2: " + (x * 2)); } var numbers = [15, 1, -15]; // Use forEach function to iterate an array. // ... Pass name of function to forEach. numbers.forEach(handleElement);FOREACH: 15 FOREACH TIMES 2: 30 FOREACH: 1 FOREACH TIMES 2: 2 FOREACH: -15 FOREACH TIMES 2: -30
Sort
In Node.js we invoke the sort()
method with an optional function argument. We can specify sorting orders. A descending sort can be applied.
In Node we can use arrays to store a few objects or elements. But for applications where many numbers are required a typed array like Int32Array
is more efficient.
For arrays, we add elements with push()
. We use keywords like the for
-keyword to loop over elements. Arrays are common and effective in Node.js programs.