DEV Community

Farah Ismah Hana
Farah Ismah Hana

Posted on

Looping and Modifying Nested Arrays in JavaScript

Introduction

When working with a nested array, we may have many values stored in different groups.

For example, imagine we have several groups of numbers and want to display all of them. We could access each value one by one, but that can become inconvenient, especially when the data gets larger.

Instead, we can use a loop to go through the values for us. This allows us to perform the same action on multiple items without writing the same code over and over.

With a nested array, there is one more thing to consider. The values are stored inside inner arrays, so we need to go through each inner array before we can work with the values inside it.

In this article, we will look at three ways to loop through a nested array using for, for...of, and forEach(). We will also see how loops can be used to process and modify the values.

Looping Through Nested Arrays

Since a nested array contains inner arrays, we need to go through more than one level to reach the values inside them.

Let's start with a for loop. We can use one loop to go through the inner arrays and another loop to go through the values inside each array.

Using for

const numbers = [
  [10, 20, 30],
  [40, 50, 60]
];

for (let i = 0; i < numbers.length; i++) {
  for (let j = 0; j < numbers[i].length; j++) {
    console.log(numbers[i][j]);
  }
}
Enter fullscreen mode Exit fullscreen mode

The output is:

10
20
30
40
50
60
Enter fullscreen mode Exit fullscreen mode

Here, the two loops work together.

The outer loop goes through each inner array, while the inner loop goes through the values inside the current array.

The length property tells us how many items an array contains. In this example, numbers.length is 2 because there are two inner arrays.

The variable i keeps track of the current inner array, while j keeps track of the current value inside that array.

For example:

i = 0 → [10, 20, 30]
    j = 0 → 10
    j = 1 → 20
    j = 2 → 30

i = 1 → [40, 50, 60]
    j = 0 → 40
    j = 1 → 50
    j = 2 → 60
Enter fullscreen mode Exit fullscreen mode

One useful thing about for is that we have direct access to the indexes. This can be helpful when we need to know where a value is located or want to use its position later.

Using for...of

But what if we do not need the indexes?

If we only need the values, for...of can make the code a little simpler:

const numbers = [
  [10, 20, 30],
  [40, 50, 60]
];

for (const group of numbers) {
  for (const number of group) {
    console.log(number);
  }
}
Enter fullscreen mode Exit fullscreen mode

The loop goes through the same values as the previous example.

Here, group represents the current inner array, while number represents each value inside that group.
We use const because we do not need to change these variables inside the loop. The loop automatically provides the next value on each iteration.

We do not need to manage i and j, so the code can be easier to follow when the indexes are not important.

Using forEach()

Another way to go through a nested array is with forEach().

forEach() runs a function for each item in an array. With a nested array, we can use it twice: the first forEach() goes through the inner arrays, and the second goes through the values inside each array.

const numbers = [
  [10, 20, 30],
  [40, 50, 60]
];

numbers.forEach((group) => {
  group.forEach((number) => {
    console.log(number);
  });
});
Enter fullscreen mode Exit fullscreen mode

The first forEach() goes through each group, while the second goes through each number inside the current group.

Now that we know a few ways to loop through a nested array, we can use those loops to do more than just access the values.

Processing Data with Loops

For example, we can use a loop to calculate the total of all the numbers:

const numbers = [
  [10, 20, 30],
  [40, 50, 60]
];

let total = 0;

numbers.forEach((group) => {
  group.forEach((number) => {
    total += number;
  });
});

console.log(total);
Enter fullscreen mode Exit fullscreen mode

The output is:

210
Enter fullscreen mode Exit fullscreen mode

The total variable starts at 0. Each time the loop reaches a number, that value is added to total.

We can use a similar approach for other tasks, such as counting values or performing calculations.

Sometimes, though, we need to change the values instead of just reading or calculating them.

Modifying Values in Nested Arrays

If we know the position of a value, we can update it using its indexes.

For example, we can change 20 to 25:

const numbers = [
  [10, 20, 30],
  [40, 50, 60]
];

numbers[0][1] = 25;

console.log(numbers);
Enter fullscreen mode Exit fullscreen mode

The output is:

[
  [10, 25, 30],
  [40, 50, 60]
]
Enter fullscreen mode Exit fullscreen mode

numbers[0] selects the first inner array, and [1] selects the second value inside it.

So, the value 20 is replaced with 25.

That works well when we only need to change one value. But if we need to update several values, doing it one by one would not be practical. We can use a nested loop instead.

For example, we can multiply every value by 2:

const numbers = [
  [10, 20, 30],
  [40, 50, 60]
];

for (let i = 0; i < numbers.length; i++) {
  for (let j = 0; j < numbers[i].length; j++) {
    numbers[i][j] *= 2;
  }
}

console.log(numbers);
Enter fullscreen mode Exit fullscreen mode

The output is:

[
  [20, 40, 60],
  [80, 100, 120]
]
Enter fullscreen mode Exit fullscreen mode

The nested loops go through each value and update it by multiplying it by 2.

So, loops are not only useful for accessing values. They can also help us process and update multiple values in a nested array.

Key Takeaways

  • Loops make it easier to work with multiple values.
  • Nested arrays can be processed using nested loops.
  • for is useful when we need to work with indexes.
  • for...of lets us work directly with values.
  • forEach() provides another way to run an action for each value.
  • Loops can be used to process and modify values inside a nested array.

Conclusion

Working with a nested array means dealing with more than one level of data. Instead of accessing each value individually, we can use loops to move through the inner arrays and work with their values.

The approach we choose depends on what we need. for gives us access to indexes, while for...of and forEach() let us focus more directly on the values.

Once we are comfortable moving through nested arrays, we can use loops for different tasks, from simple calculations to updating multiple values.

In the next article, we will look at another way to work with nested arrays by flattening them into a simpler structure.

Top comments (0)