Code Highlights logo

Learn

Arrays

Nested Arrays

A nested array is simply an array that contains other arrays as its elements. This allows us to create a multidimensional structure, similar to a table or grid, where each element can hold its own set of values.

Creating Nested Arrays

To create a nested array, you can simply include arrays as elements within an outer array. Here's an example:

1let nestedArray = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5];

In the above code snippet, we have created a nested array called nestedArray with three inner arrays.

Accessing Elements in Nested Arrays

Accessing elements in nested arrays requires an extra level of indexing. You can access a specific element by using square brackets [] and specifying the index of both the outer array and the inner array. Here's an example:

1let nestedArray = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5];
6
7console.log(nestedArray[1][2]); // Outputs: 6

In the above code snippet, we accessed the element with index 1 in the outer array, and then accessed the element with index 2 in the inner array.

Modifying Elements in Nested Arrays

Modifying elements in nested arrays follows the same principle as accessing them. You can assign new values to specific elements by using the indexing syntax. Here's an example:

1let nestedArray = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5];
6
7nestedArray[0][1] = 10;
8console.log(nestedArray); // Outputs: [[1, 10, 3], [4, 5, 6], [7, 8, 9]]

In the above code snippet, we modified the element at index 1 in the first inner array to have a new value of 10.


Instructions

1.

Create a variable called firstElement and set it equal to the first element of the nested array.

2.

Create a variable called lastElement and set it equal to the last element of the nested array.

3.

Create a variable called middleElement and set it equal to the middle element of the nested array.

Sign up to start coding

Already have an account?

Sign In

Course content