HomeSearch

JavaScript Array Examples

Create new arrays and add elements with methods like push. Get the length to count elements.

Array.

In the deep winter snow falls. It packs onto trees and the earth. As the blizzard continues the snow builds up. It is added to.

An array

stores one element after another. It is a linear collection of elements. Like snow it can keep expanding. We initialize with square brackets. We use push() to add.Initialize Array

Simple example.

Here we see an array literal with 3 elements. We can access the length of the array with the length property. Here we have a 3-element array.
JavaScript program that uses array var numbers = [10, 20, 30]; // Print the array elements. console.log("ARRAY: " + numbers); // Get length of array. var length = numbers.length; console.log("LENGTH: " + length); Output 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.
JavaScript program that uses push // 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); Output 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.

JavaScript program that uses initial array size // Use new Array with one integer to have undefined elements. var result = new Array(5); console.log("ARRAY: " + result); Output 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.

JavaScript program that uses pop var colors = ["red", "blue", "green"]; // Remove last element from the array. var removed = colors.pop(); console.log("COLORS: " + colors); console.log("REMOVED: " + removed); Output 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.
JavaScript program that uses indexOf 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); Output 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.

JavaScript program that uses lastIndexOf 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); Output 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.
JavaScript program that uses for-loop on 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]); } Output 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.

JavaScript program that uses for-in loop on array var letters = ["g", "h", "i"]; // Loop over indexes with for-in loop. for (var i in letters) { console.log("FOR IN: " + letters[i]); } Output 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.
JavaScript program that uses for-of loop on array var sides = ["left", "center", "right"]; // Loop over elements with for-of. for (var side of sides) { console.log("FOR OF: " + side); } Output 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).
JavaScript program that uses slice 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); Output 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.

JavaScript program that uses splice 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); Output 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.

JavaScript program that uses reverse var colors = ["blue", "red"] // Reverse the ordering of the array. // ... The original is modified. var reversed = colors.reverse(); console.log("REVERSED: " + colors); Output 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.
JavaScript program that accesses adjacent elements 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); } Output 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).

JavaScript program that uses sparse array // 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]); Output 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.

JavaScript program that uses shift 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); Output 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.

JSON: For a way to convert an array into a string format that can be reused with no data loss, consider JSON.stringify.

JSON
JavaScript program that uses toString 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); Output 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.

JavaScript program that uses join var vehicles = ["car", "train", "plane", "boat"]; // Join with a delimiter character. var result = vehicles.join("/"); console.log("JOINED: " + result); Output 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.

JavaScript program that uses forEach function on array function handleElement(x) { "use strict"; // 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); Output FOREACH: 15 FOREACH TIMES 2: 30 FOREACH: 1 FOREACH TIMES 2: 2 FOREACH: -15 FOREACH TIMES 2: -30

Push, unshift benchmark.

Here we test adding 1000 numbers to an array. The first version uses push, and the second version uses unshift. The total time required is recorded for each page.

Note: The data in the "numbers" array is different for the pages, but the same total count of elements is added in both.

Analysis: When adding elements to an array, push() is a faster option than unshift. Push is optimized better in browsers.

JavaScript program that uses array, push // Push adds to the end of an array. var test = []; test.push(1); test.push(2); var x1 = performance.now(); for (i = 0; i < 1000; i++) { // Create an array and push 1000 numbers to it. var numbers = []; for (var x = 0; x < 1000; x++) { numbers.push(x); } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + test; JavaScript program that uses array, unshift // Insert elements at start of array with unshift. var test = []; test.unshift(1); test.unshift(2); var x1 = performance.now(); for (i = 0; i < 1000; i++) { // Use unshift to add 1000 integers. var numbers = []; for (var x = 0; x < 1000; x++) { numbers.unshift(x); } } var x2 = performance.now(); document.title = (x2 - x1) + "/" + test; Output 6.18 ms push 146.09 ms unshift

Array creation benchmark.

Suppose we want to create a 1-element array with a certain value in it. We can use the literal syntax or use an empty array and call push().

Result: Using a single expression with literal syntax is faster in Chrome. Reducing method calls (like push) tends to help performance.

JavaScript program that times literal with 1 element var x1 = performance.now(); // Create 1-element array with literal syntax. for (var i = 0; i < 10000000; i++) { var test = [1]; } var x2 = performance.now(); document.title = x2 - x1; JavaScript program that times empty array, push var x1 = performance.now(); // Create 1-element array with empty literal and push. for (var i = 0; i < 10000000; i++) { var test = []; test.push(1); } var x2 = performance.now(); document.title = x2 - x1; Output 1000.455 ms 1-element literal 1522.295 ms 0-element literal, push()

Push benchmark.

We can append elements to an array with push() or by assigning to the next element. The JavaScript array will resize to fit the new element.

Question: Is it faster to use push() or to assign to the next element? And does the difference matter?

Answer: In Chrome I found that assignment performs lightly better. But even in a long-running simulation this difference is small.

JavaScript program that benchmarks push var x1 = performance.now(); // Append to an array with push. for (var i = 0; i < 1000000; i++) { var test = []; for (var x = 0; x < 10; x++) { test.push(5000); } } var x2 = performance.now(); document.title = x2 - x1; JavaScript program that benchmarks assignment var x1 = performance.now(); // Append to an array with assignment. for (var i = 0; i < 1000000; i++) { var test = []; for (var x = 0; x < 10; x++) { test[x] = 5000; } } var x2 = performance.now(); document.title = x2 - x1; Output 752 ms push 722 ms 767 ms 735 ms assign 640 ms 626 ms

Initial size benchmark.

We can improve performance by specifying an initial array size and then assigning the undefined elements. Here we test two programs.

Program 1: This uses an empty array literal and appends 200 elements with the push method.

Program 2: This one uses "new Array(200)" and assigns the 200 undefined elements. The array should never resize.

Result: Program 2 is faster as the array is never resized—it has all 200 elements at creation time and never resizes, unlike program 1.

JavaScript program that uses empty array var x1 = performance.now(); for (var i = 0; i < 1000000; i++) { // Add 200 elements to an empty array. var result = []; for (var x = 0; x < 200; x++) { result.push(x); } } var x2 = performance.now(); document.title = (x2 - x1); JavaScript program that uses initial size var x1 = performance.now(); for (var i = 0; i < 1000000; i++) { // Create 200 undefined elements and assign them. var result = new Array(200); for (var x = 0; x < 200; x++) { result[x] = x; } } var x2 = performance.now(); document.title = (x2 - x1); Output 814.16 ms Empty array, push 541.03 ms Array(200), assign

Sort.

In JavaScript we invoke the sort() method with an optional function argument. We can specify sorting orders. A descending sort can be applied.Sort

For, array benchmark.

A for-loop from 0 to the length of an array tends to perform well in Google Chrome. More complex loops (while, or ones with hoisted variables) are harder to optimize.for

Typed arrays.

In JavaScript 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

Split.

We can use split() to get a string array from a string that contains delimiter characters. This is a way an array can be represented in a more compact way in a web page.split

Linked list.

Arrays can be used to create a linked list—each list item is a 2-element array. One of the array elements is a reference to another unit in the linked list.Linked List

For arrays,

we add elements with push. We use keywords like "for" to loop over elements. Arrays are common and effective in JavaScript programs.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.