Javascript Arrays| Working with Arrays

Javascript Arrays| Working with Arrays

JavaScript arrays work like arrays in most other programming languages. The following example shows how you can create and populate an array.

let myArray = new Array();
myArray[0] = 100;
myArray[1] = "Adam";
myArray[2] = true;

I have created a new array by calling a new Array(). This creates an empty array, which I assign to the variable myArray. In the subsequent statements, I assign values to various index positions in the array. (There is no console output from this listing.)

There are a couple of things to note in this example. First, I didn’t need to declare the number of items in the array when I created it. JavaScript arrays will resize themselves to hold any number of items. The second point is that I didn’t have to declare the data types that the array will hold. Any JavaScript array can hold any mix of data types. In the example, I have assigned three items to the array: a number, a string, and a boolean.

Using an Array Literal

The array literal style lets you create and populate an array in a single statement, as shown in the following example.

let myArray = [100, "Adam", true];

In this example, I specified that the myArray variable should be assigned a new array by specifying the items I wanted in the array between square brackets ([ and ]). (There is no console output from this listing.)

Reading and Modifying the Contents of an Array

You read the value at a given index using square braces ([ and ]), placing the index you require between the braces, as shown in the following example.

let myArray = [100, "Adam", true];
console.log("Index 0: " + myArray[0]);

You can modify the data held in any position in a JavaScript array simply by assigning a new value to the index. Just as with regular variables, you can switch the data type at an index without any problems. The output from the listing is as follows:

Index 0: 100

The following example demonstrates modifying the contents of an array

let myArray = [100, "Adam", true];
myArray[0] = "Tuesday";
console.log("Index 0: " + myArray[0]);

In this example, I have assigned a string to position 0 in the array, a position that was previously held by a number and produces this output:

Index 0: Tuesday



Enumerating the Contents of an Array

You enumerate the content of an array using a for loop or using the forEach method, which receives a function that is called to process each element in the array. Both approaches are shown in the following example.

let myArray = [100, "Adam", true];
myArray[0] = "Tuesday";
console.log("Index 0: " + myArray[0]);

In this example, I have assigned a string to position 0 in the array, a position that was previously held by a number and produces this output:

Index 0: Tuesday

Enumerating the Contents of an Array

You enumerate the content of an array using a for loop or using the forEach method, which receives a function that is called to process each element in the array. Both approaches are shown in the following example

let myArray = [100, "Adam", true];
for (let i = 0; i < myArray.length; i++) {
 console.log("Index " + i + ": " + myArray[i]);
}
console.log("---");
myArray.forEach((value, index) => console.log("Index " + index + ": " + value));

The JavaScript for loop works just the same way as loops in many other languages. You determine how many elements there are in the array by using the length property.

The function passed to the forEach method is given two arguments: the value of the current item to be processed and the position of that item in the array. In this listing, I have used an arrow function as the argument to the forEach method, which is the kind of use for which they excel (and you will see used throughout this book). The output from the listing is as follows:

Index 0: 100

Index 1: Adam

Index 2: true

Index 0: 100

Index 1: Adam

Index 2: true

Using the Spread Operator

The spread operator is used to expand an array so that its contents can be used as function arguments or combined with other arrays. In the following example, I used the spread operator to expand an array so that its items can be combined into another array.

let myArray = [100, "Adam", true];
let otherArray = [...myArray, 200, "Bob", false];
for (let i = 0; i < otherArray.length; i++) {
 console.log(`Array item ${i}: ${otherArray[i]}`);
}
The spread operator is an ellipsis (a sequence of three periods), and it causes the array to be unpacked.
...
let otherArray = [...myArray, 200, "Bob", false];
...

Using the spread operator, I am able to specify myArray as an item when I define another array, with the result that the contents of the first array will be unpacked and added as items to the second array. This example produces the following results:

Array item 0: 100

Array item 1: Adam

Array item 2: true

Array item 3: 200

Array item 4: Bob

Array item 5: false

Using the Built-in Array Methods

The JavaScript Array object defines a number of methods that you can use to work with arrays, the most useful of which are described in the following table.

MethodDescription
concat(otherArray) This method returns a new array that concatenates the array on which it has been called with the array specified as the argument. Multiple arrays can be specified.
join(separator) This method joins all the elements in the array to form a string. The argument specifies the character used to delimit the items.
pop() This method removes and returns the last item in the array.
shift() This method removes and returns the first element in the array.
push(item) This method appends the specified item to the end of the array.
unshift(item) This method inserts a new item at the start of the array.
reverse() This method returns a new array that contains the items in reverse order.
slice(start,end) This method returns a section of the array.
sort() This method sorts the array. An optional comparison function can be used to perform custom comparisons.
splice(index, count) This method removes count items from the array, starting at the specified index. The removed items are returned as the result of the method.
unshift(item) This method inserts a new item at the start of the array.
every(test) This method calls the test function for each item in the array and returns true if the function returns true for all of them and false otherwise.
some(test) This method returns true if calling the test function for each item in the array returns true at least once.
filter(test) This method returns a new array containing the items for which the test function returns true.
find(test) This method returns the first item in the array for which the test function returns true.
findIndex(test) This method returns the index of the first item in the array for which the test function returns true.
foreach(callback) This method invokes the callback function for each item in the array, as described in the previous section.
includes(value) This method returns true if the array contains the specified value.
map(callback) This method returns a new array containing the result of invoking the callback function for every item in the array.
reduce(callback) This method returns the accumulated value produced by invoking the callback function for every item in the array.

Since many of the methods in the above table return a new array, these methods can be chained together to process a filtered data array, as shown in the following example.

let products = [
 { name: "Hat", price: 24.5, stock: 10 },
 { name: "Kayak", price: 289.99, stock: 1 },
 { name: "Soccer Ball", price: 10, stock: 0 },
 { name: "Running Shoes", price: 116.50, stock: 20 }
];
let totalValue = products
 .filter(item => item.stock > 0)
 .reduce((prev, item) => prev + (item.price * item.stock), 0);
console.log("Total value: $" + totalValue.toFixed(2));

I use the filter method to select the items in the array whose stock value is greater than zero and use the reduce method to determine the total value of those items, producing the following output:

Total value: $2864.99



Leave a Reply

Close Menu