JS: Arrays
Theory: Nested loops
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:
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:
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.
An example of putting flatten's code into a separate function:
Recommended programs
Completed
0 / 22

