Home
Node.js
Array Examples
This page was last reviewed on May 15, 2023.
Dot Net Perls
Array. 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.
Shows an array
Array details. We initialize with square brackets. We use call the push() method to add. Modern JavaScript runtimes (like Node) optimize operations on arrays.
Array Initialize
First example. 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.
Part 1 Here we print the array elements by passing the string representation of the array to console.log.
Part 2 Each array has a length, and this is precomputed for the array, so no looping or counting must occur.
Shows an array
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
Push. 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
Initial size. 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.
Tip This is like an array capacity, but all the initial elements exist and are undefined.
// Use new Array with one integer to have undefined elements. var result = new Array(5); console.log("ARRAY: " + result);
ARRAY: ,,,,
Pop. 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.
Tip 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.
Here We have 3 "blue" strings in an array. We find the last one with 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-loop. Here 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.
for
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 loop. With 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.
Tip With the for-in loop on an array, we must still access the element with an index. The iteration variable is an index.
Note The array indexes can be returned in any order by the 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 loop. This 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
Slice. 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
Splice. 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.
Argument 1 The index we want to start removing from. So to remove the second element onwards, we pass 1.
Argument 2 The count of elements we want to remove. To remove 2 elements we pass the value 2.
Finally We pass any number of arguments to be inserted in the region specified. The array grows to accommodate these elements.
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.
Note Arrays are mutable in JavaScript. Unlike strings, we can modify them in-place with no copies.
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
Adjacent elements. 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
Sparse array. 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.
And This saves memory. Engines like V8 decide when to use sparse arrays with logical rules (heuristics).
// 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
Shift. 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.
Note It is possible to modify arrays. But often for best performance, leaving arrays alone and using indexes to access them is best.
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.
Note No quotes are in the output string. So if a string contains a comma, it may be impossible to convert this string back into an array.
Detail For a way to convert an array into a string format that can be reused with no data loss, consider JSON.stringify.
JSON.parse
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).
Tip 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 function. Looping over the elements in an array can be done with the forEach function. We must provide a function argument that handles each element.
function
Here We call forEach on an array, and call the handleElement function on each individual element.
Tip Using 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.
Array sort
Typed arrays. 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.
Int32Array
For arrays, we add elements with push. We use keywords like "for" to loop over elements. Arrays are common and effective in Node.js programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 15, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.