In JavaScript, when an inner array or sub-array is added to an array, it is known as a “Multi-dimensional” or “Nested” array. JavaScript does not provide an explicit format to create a nested array; therefore, we need to nest the required sub-arrays within a single outer array. Also, the elements of inner arrays are accessed based on their index in the outer array.

After declaring a nested array in JavaScript, you can perform different operations on it, such as appending sub-arrays, accessing the elements of the sub-arrays, iterating over all of the sub-arrays elements, deleting a sub-array, or its related element, and reducing the dimensionality of the nested array.

This write-up will explain the working of the nested arrays in JavaScript with the help of suitable examples. So, let’s start!

<img alt="up" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/up.png" data-lazy- height="1558" src="data:image/svg xml,” width=”1101″>

How to create a nested array in JavaScript

To create a nested array in JavaScript, you have to follow the below-given syntax:

let array = [ [inner_array1], [inner_array2], [inner_array3]….];

Here “array” represents the nested array that contains multiple inner-arrays such as “inner_array1”, “inner_array2”, “inner_array3”.

Example: How to create a nested array in JavaScript

We will create a multi-dimensional or nested array named “hobbies” that further comprises five inner arrays:

let hobbies= [

[‘Reading’, 4],

[‘Gardening’, 2],

[‘Gaming’, 1],

[‘Painting’, 8],

[‘Cooking’, 5]

];

In the declared “hobbies” array, the added first dimension represents the “hobby,” and the second indicates the maximum number of “hours” spent while doing that activity.

Now, to display the created “hobbies” nested array, we will utilize the “console.table()” method while passing the “hobbies” array as an argument:

Execution of the above-given code will show the values of the “hobbies” array in a table format, where the first column represents the index of inner arrays and the other two columns contain their elements that are present at the first “[0]” and second “[1]” index:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-28.png" data-lazy- height="538" src="data:image/svg xml,” width=”919″>

How to access elements of nested arrays in JavaScript

Need to access the elements of a nested array? If yes, then have a look at the below-given syntax:

Here, “a” represents the index of the “inner” array in the created nested array, and “b” represents the index of the “element” in the specified inner or sub-array.

Example: How to access elements of nested arrays in JavaScript

For instance, we want to access the “Cooking” hobby that exists as the “First” element “[0]” of the fifth inner array “[4]”:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-29.png" data-lazy- height="215" src="data:image/svg xml,” width=”703″>

To perform the specified operation, we will execute the below-given code statement:

console.log(hobbies[4][0]);

As you can see from the output, we have successfully accessed the value of the “hobbies” array that is placed at the first index of the fifth inner array:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-30.png" data-lazy- height="151" src="data:image/svg xml,” width=”710″>

How to add elements to nested array in JavaScript

JavaScript offers two ways for adding elements to an already created nested array; either you can append an element at the end of an array using the “push()” method or insert it at a specific position with the help of the “splice()” method.

Example: How to add elements to nested array in JavaScript

To push the “[Cycling, 6]” sub-array as at the end of the “hobbies” nested array, we will pass it as an argument to the “hobbies.push()” method:

hobbies.push([‘Cycling’, 6]);

console.table(hobbies);

When the given “hobbies.push()” gets executed, it will add the specified sub-array at the end of the “hobbies” array:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-31.png" data-lazy- height="449" src="data:image/svg xml,” width=”743″>

Whereas, to insert a sub-array in the middle of other inner arrays, utilize the “splice()” method in the following way:

hobbies.splice(1, 0, [‘Singing’, 3]);

console.table(hobbies);

Here, the “hobbies.splice()” method will overwrite the “hobbies” array and add the “[‘Singing’, 3]” sub-array at the second position:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-32.png" data-lazy- height="458" src="data:image/svg xml,” width=”823″>

Till this point, we have learned the procedure to create a nested array and add elements to it. In the next section, we will talk about iterating over the elements of a nested array in JavaScript.

How to iterate over the elements of nested array in JavaScript

You may know that the JavaScript “for” loop is primarily utilized to iterate over the elements of an array. However, as in our case, we have a “nested” array, so we will add two “for” loops nested within the other.

Example: How to iterate over the elements of nested array in JavaScript

The first loop “for” loop will iterate over the outer array elements according to its size and its nested “for” loop will perform the iteration over the inner sub-arrays:

for (leti = 0; i<hobbies.length; i ) {


    varinnerArrayLength = hobbies[i].length;


     for (let j = 0; j <innerArrayLength; j ) {


        console.log(‘[‘ i ‘,’ j ‘] = ‘ hobbies[i][j]);


    }

}

The specified iteration operation will display all of the elements of the “hobbies” nested array:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-33.png" data-lazy- height="549" src="data:image/svg xml,” width=”679″>

You can also use the “ForEach()” method for the same purpose.

How to flatten a nested array in JavaScript

There are certain scenarios in which you may need to create an array that comprises all of the nested JavaScript array elements in their original order. If that’s the case, then flatten the created nested array to reduce its dimensionality.

The “Array.flat()” method is embedded in ES6, which assists in flattening a nested JavaScript Array. This method returns a new array after concatenating all of the sub-arrays elements.

Example: How to flatten a nested array in JavaScript

For instance, to flatten the “hobbies” array, we will execute the following code in the console window:

const flatArray= hobbies.flat();

console.log(flatArray);

The given “hobbies.flat()” method will reduce the dimensionality of the “hobbies” array and flatten the elements of the inner array:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-34.png" data-lazy- height="214" src="data:image/svg xml,” width=”984″>

How to delete elements of nested array in JavaScript

To remove elements from any sub-arrays of a nested array, use the “pop()” method. The “pop()” method typically deletes the last inner-array from a nested array; however, it also helps in removing elements from inner arrays.

Example: How to delete elements of nested array in JavaScript

Before utilizing the “pop()” method, we have the following sub-arrays in the “hobbies” nested array:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-35.png" data-lazy- height="270" src="data:image/svg xml,” width=”845″>

Now when we invoke the “pop()” method, the last sub-array will be deleted along with its elements:

hobbies.pop();

console.table(hobbies);

Output

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-36.png" data-lazy- height="411" src="data:image/svg xml,” width=”1014″>

To remove the second element of each “sub-array”, we will iterate through the “hobbies” array using the “forEach()” method, and at each iteration the “pop()” method deletes the element positioned at the first index:

hobbies.forEach((hobby) => {


    hobby.pop(1);

});


console.table(hobbies);

It can be seen in the below-given output that the element representing the maximum number of hours spent on each hobby is deleted for all sub-arrays:

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-37.png" data-lazy- height="475" src="data:image/svg xml,” width=”891″>

We have compiled all essential information related to the working of nested arrays in JavaScript. You can further explore them according to your preferences.

Conclusion

When an inner array or sub-array is added to an outer array, it is called a nested array. After creating a JavaScript nested array, you can use the “push()” and “splice()” method for adding elements, “for loop” and “forEach()” method to iterate over the elements of the inner arrays, “flat()” method for reducing the dimensionality, and “pop()” method to delete sub-arrays or their elements from the nested arrays. This write-up explained the working of nested loops in JavaScript.

About the author

<img alt="" data-lazy-src="https://secure.gravatar.com/avatar/c73b74cd8044d2e9b300610f5af77d0b?s=112&r=g" data-lazy- height="112" src="data:image/svg xml,” width=”112″>

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.