Given a multidimensional array of arbitrary nesting level, for example, this:
let arr = [
1,
[
2, 7, 8
],
[
3, 4, [5, [6, 7]],
]
];
As you can see, this array has a complex structure, and it is assumed that this structure can be arbitrary and nesting levels can be arbitrarily deep.
Let's say we want to output to the console all the primitive (i.e., non-array) elements of our array. In this case, we simply cannot use loops to iterate over such an array, since the array has a not ordinary structure and an unknown nesting level.
But to iterate over such an array, it will be very convenient to use recursion.
To begin with, we will make a function into which we will pass our array as a parameter, and in the function we will make a loop to iterate over our array:
function func(arr) {
for (let elem of arr) {
console.log(elem);
}
}
func([1, [2, 7, 8], [3, 4, [5, [6, 7]]]]);
The loop we made will only iterate over
the elements of the main array. That is,
first it will print 1
, then [2, 7, 8]
,
and then [3, 4, [5, [6, 7]]ā
/cā.
Let's now separate primitive elements and array elements in a cycle:
function func(arr) {
for (let elem of arr) {
if (typeof elem == 'object') {
// element - array
} else {
// element - primitive
console.log(elem);
}
}
}
func([1, [2, 7, 8], [3, 4, [5, [6, 7]]]]);
And now let's make it so that if our element is an array, the function calls itself, passing this array as a parameter:
function func(arr) {
for (let elem of arr) {
if (typeof elem == 'object') {
func(elem);
} else {
console.log(elem);
}
}
}
func([1, [2, 7, 8], [3, 4, [5, [6, 7]]]]);
Given a multidimensional object of arbitrary nesting level, for example, this one:
{a: 1, b: {c: 2, d: 3, e: 4}, f: {g: 5, j: 6, k: {l: 7, m: {n: 8, o: 9}}}}
Use recursion to print all the primitive elements of this object to the console.
Given a multidimensional array of arbitrary nesting level, for example, this:
[1, [2, 7, 8], [3, 4, [5, [6, 7]]]]
Write code that will convert our multi-dimensional array into a one-dimensional one. For the above array it will look like this:
[1, 2, 7, 8, 3, 4, 5, 6, 7]