Multidimensional arrays in JavaScript

Array elements can be not only strings and numbers, but also arrays. In this case, we get an array of arrays, or a multidimensional array.

In the following example, the array arr consists of three elements, which in turn are arrays:

let arr = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']];

Let's rewrite in a more understandable way:

let arr = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ];

Depending on the level of nesting, arrays can be two-dimensional - an array of arrays, three-dimensional - an array of arrays of arrays (and so on - four-dimensional, five-dimensional, etc.).

The above array is two-dimensional, since there are other sub-arrays inside one array, and there are no other arrays already in these sub-arrays.

To display any element from a two-dimensional array, you should write not one pair of square brackets, but two:

let arr = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ]; console.log(arr[0][1]); // shows 'b' console.log(arr[1][2]); // shows 'f'

Given the following array:

let arr = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'], ];

Use it to output elements with the text 'l', 'e', 'g' and 'a'

Given the following array:

let arr = [[1, 2], [3, 4], [5, 6]];

Referring to each array element, find the sum of all its elements.

Three-dimensional array

Here is an example of a 3D array:

let arr = [ [ ['a', 'b'], ['c', 'd'], ], [ ['e', 'f'], ['g', 'h'], ], [ ['i', 'j'], ['k', 'l'], ], ];

To display elements from such an array, you already need to write three square brackets pairs:

console.log(arr[0][0][0]); // shows 'a' console.log(arr[2][1][0]); // shows 'k'

Given the following array:

let arr = [ [ [1, 2], [3, 4], ], [ [5, 6], [7, 8], ], ];

Referring to each element of the array, find the sum of all its elements.

Arbitrary arrays

Multidimensional arrays do not have to be the same as we discussed above. Look at the following array for example:

let arr = [['a', 'b', [1, 2, 3], [4, 5]], ['d', ['e', 'f']]];

As you can see, this array is "unusual". It contains arrays ([1, 2, 3] and ā… cā†[4, 5]) next to regular elements (for example, 'a', 'b'). Let's rewrite our array in a more understandable way:

let arr = [ [ 'a', 'b', [1, 2, 3], [4, 5], ], [ 'd', ['e', 'f'], ], ];

Given the following array:

let arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];

Manually - without a loop, find the sum of this array elements.

enru