1. Code
  2. JavaScript

Working With Nested Arrays in JavaScript

Scroll to top
4 min read

If you’re finding it difficult to understand and work with multidimensional arrays or nested arrays in JavaScript, then you’re in the right place. In this article, we’ll dive into nested arrays and go over the methods for updating, adding, and removing items in a multidimensional array.

JavaScript Arrays

A JavaScript array is a collection of data that is stored in a list-like structure. Arrays are indexed—this means that each item in the array can be accessed using an index, which is an integer starting from 0.

For example, a simple array could look like this:

1
  let myArray = [1, 2, 3, 4, 5]; 

In this example, the first item in the array has an index of 0, the second item has an index of 1, and so on.

Arrays are most commonly used to store collections of data that need to be accessed quickly and easily. For example, if you have a list of users in your application, you could store them in an array and access them by their index.

1
let users = ["John", "Jane", "Jack"];console.log(users[0]); // Outputs: "John"

They can be used to store all kinds of values, including strings, numbers, and objects. It’s perfectly valid to store these different types of values within the same array.

1
const varied = [null, undefined, NaN, "string", 12345, {name: "Sam"}]

You can also store (or nest) an array inside another array. This creates what is known as a multidimensional array.

Nested Arrays in JavaScript

A multidimensional array (also known as an array of arrays) is simply an array with one or multiple children arrays. These children arrays are said to be nested in the parent array.

1
const arrayOfArr = [  ['value 1', 'value 2']  ['value 3', 'value 4']  ['value 5', 'value 6']]

Nested arrays can be used to group related elements. For example, take a look at the following multidimensional array:

1
const animalPairs = [  // female and male  ['doe', 'buck'],   ['ewe', 'ram'],  ['peahen', 'peacock'],  ['cow', 'bull'],  ]

Here, we’re pairing up the male and female names of the same animal in each nested array. Females are to the left and males to the right.

To access the first element, you’d use the index of 0 like so:

1
animalPairs[0]

Print the result on the console:

1
console.log(animalPairs[0])// ['doe', 'buck'],

Now, to access a value from within a nested array, you have to add a second bracket containing the index of the value you want to access. For instance, let’s say you wanted to get the female name from the first array. Since you know that the female is always placed first, you simply:

  • use [0] to get the first nested array
  • then chain another [0] to get the first element inside that nested array (in our case, the female name):
1
animalPairs[0][0]

Here’s the output:

1
console.log(animalPairs[0][0])// 'doe'

If you want to get the second item in the first nested array:

1
animalPairs[0][1] // 'buck'

In this case, we only have two items in each nested array, so our index terminates at [1]. If you add more items, you can access each of them by their index.

To summarize, the first [ ] returns the nested array, while the second [ ] returns a value from within that nested array.

IllustrationIllustrationIllustration
Illustration

Updating Elements in the Nested Array

Let’s say that I was wrong about the first item, and the name of a male rabbit is "stag" and not "buck". I can easily update the array by accessing the index and reassigning “stag” to it, like so:

1
animalPairs[0][1] = 'stag'

Here's the output:

1
console.log(animalPairs[0])// ['doe', 'stag'], 

You can also reassign a whole array (and not just one of its values) to a particular position in the main array using the index. This example changes the first nested array from rabbit to chicken:

1
animalPairs[0] = ['hen', 'rooster']

Adding and Removing Nested Arrays

You can nest a new array at the beginning and ending of another array, and you can remove an existing array from the start and end position of another array.

To nest an array at the beginning of the main one, pass the array to the unshift() method:

1
const animalPairs = [  // hen and rooster will be inserted here  ['doe', 'buck'],   ['ewe', 'ram'],  ['peahen', 'peacock'],  ['cow', 'bull'],  ]animalPairs.unshift(['hen', 'rooster'])

To insert an array at the end of the parent, pass the array to the push() method:

1
const animalPairs = [  ['doe', 'buck'],   ['ewe', 'ram'],  ['peahen', 'peacock'],  ['cow', 'bull'],    // hen and rooster will be inserted here]animalPairs.push(['hen', 'rooster'])

To remove the first nested array, simply execute the shift() method on the parent array:

1
const animalPairs = [  ['doe', 'buck'], // removes this one  ['ewe', 'ram'],  ['peahen', 'peacock'],  ['cow', 'bull'],  ]animalPairs.shift()

Finally, to remove the last array, execute the pop() method on the parent array:

1
const animalPairs = [  ['doe', 'buck'],   ['ewe', 'ram'],  ['peahen', 'peacock'],  ['cow', 'bull'], // removes this one ]animalPairs.pop()

Conclusion

Using nested arrays is less common in real-world use cases. It’s much more common to nest multiple objects in an array (e.g. an array of user objects, each with properties like id, username, and so on).

However, knowing how to access and manipulate data in nested arrays helps you understand the language better. It also assists you in mastering the syntax for traversing complex array structures in JavaScript.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.