Register to get access to free programming courses with interactive exercises

Nested loops JS: Arrays

Many programming languages have a very useful function called flatten. For certain tasks, it makes life a lot easier and reduces the amount of code. This function takes an array as input and flattens it: if the elements in the array are also arrays, then flatten reduces everything to a single array, expanding each nested one. In js, this function is implemented as the flat() method for arrays:

[[3, 2], 5, 3, [3, 4, 2], 10].flat();
// [3, 2, 5, 3, 3, 4, 2, 10]

Let's implement this function ourselves. In general, this function expands arrays at all levels of nesting. But for simplicity's sake, we'll make a version of the function which only expands the first level of nesting. In other words, if an element of the main array is also an array, it'll be expanded without the function looking at its insides (there may be more arrays, too).

The logic of the function is as follows:

const flatten = (coll) => {
  const result = [];
  for (const item of coll) {
    // Array.isArray is a predicate function in the standard library,
    // which checks if the value is an array
    if (Array.isArray(item)) {
      // If the value is an array, then we'll go through all of its elements
      // A nested loop has appeared here
      for (const subItem of item) {
        // and add them to the resulting array
        result.push(subItem);
      }
    } else {
      // If the value is not an array, add it to the resulting array straight away
      result.push(item);
    }
  }

  return result;
};

console.log(flatten([3, 2, [], [3, 4, 2], 3, [123, 3]]));
// => [ 3, 2, 3, 4, 2, 3, 123, 3 ]

Note that the nested loop is only started if the current element is an array. Technically speaking, there's nothing special about nested loops. You can put them inside any block and into each other as many times as you like. But there is no direct connection between the outer loops and nested loops. The inner loop can use the results of the outer loop, or it can work independently according to its own logic.

Nested cycles are deceitful. Their presence can dramatically increase the complexity of the code, as there are many variables that are constantly changing. It becomes difficult to keep track of the processes going on inside. In addition, nested loops may indicate the use of an inefficient problem-solving algorithm. This is not always the case, but there is always the possibility.

How do I do without nested loops? There are three options. The first is to do nothing, sometimes nested loops are okay, especially in low-level algorithms. The second is to rewrite the algorithm so that there is no nested loop at all, not even in the called functions. When this is not possible, there's a third option. Turn the nested loop into a function, or replace it with a built-in function (or method). In JavaScript, for example, arrays have the includes() method, which is nothing more than a loop around an array.

// This function replaces the loop
// But don't forget that there's still a full array traversal inside
[1, 10, 3].includes(10); // true

An example of putting flatten's code into a separate function:

// Changes the first array directly
// In this case, implementing it in this way is justified
const append = (arr1, arr2) => {
  for (const item of arr2) {
    arr1.push(item);
  }
};

const flatten = (coll) => {
  const result = [];
  for (const item of coll) {
    if (Array.isArray(item)) {
      // There is no assignment to a variable because the result variable itself changes
      append(result, item);
    } else {
      result.push(item);
    }
  }

  return result;
};

flatten([3, 2, [], [3, 4, 2], 3, [123, 3]]);
// [3, 2, 3, 4, 2, 3, 123, 3]

Recommended materials

  1. Array.isArray method that checks if the value is an array
  2. Built-in array method flat
  3. Array.prototype.flat and Array.prototype.flatMap

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY