DEV Community

loading...

Create complex multi-dimensional arrays

rthefounding profile image Randy Rivera ・2 min read
  • One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a multi-dimensional, or nested array.
  • Ex:
let nestedArray = [ // level 1
  ['deep'], //level 2
  [
    ['deeper'], ['deeper'] //level 3
  ],
  [
    [
      ['deepest'], ['deepest'] //level 4
    ],
    [
      [
        ['deepest-est?'] //level 5
      ]
    ]
  ]
];
Enter fullscreen mode Exit fullscreen mode
  • The deep array is nested 2 levels deep. The deeper arrays are 3 levels deep. The deepest arrays are 4 levels, and the deepest-est? is 5.
  • While this example may seem difficult, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data. However, we can still very easily access the deepest levels of an array this complex with bracket notation.
console.log(nestedArray[2][1][0][0][0]); This logs the string deepest-est?
Enter fullscreen mode Exit fullscreen mode
  • Let's look at another example.
let myNestedArray = [ /Level 1
  ['unshift', false, 1, 2, 3, 'complex', 'nested'],
  [
    'loop',
    'shift',
     6,
     7,
     1000,
     'method',
     ['deep',
       [ 'deeper',
         ['deepest']  
       ]
     ]
  ],
  ['concat', false, true, 'spread', 'array'],
  ['mutate', 1327.98, 'splice', 'slice', 'push'],
  ['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth']
];
Enter fullscreen mode Exit fullscreen mode
  • We have defined a variable, myNestedArray, set equal to an array. myNestedArray has a combination of strings, numbers, and booleans for data elements. Somewhere on the third level, I included the string deep, on the fourth level, include the string deeper, and on the fifth level, include the string deepest.
console.log(myNestedArray[1][6][1][1][0]); // will display deepest
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app