-3

Nested Array in JavaScript is defined as Array (Outer array) within another array (inner array). An Array can have one or more inner Arrays. These nested array (inner arrays) are under the scope of outer array means can i access these inner array elements based on outer array name?

const favMovies = [
    'Begin Again', 'Soul',
    ['Matrix', 'Matix Reloaded', 'Matrix Revolutions'],
    ['Frozen', 'Frozen 2',
        ['Tangled', 'Alladin']
    ]
]

can i access these inner array elements based on outer array name with favMovies?

kelsny
  • 23,009
  • 3
  • 19
  • 48
theaminuldev
  • 109
  • 8
  • 1
    Yes; to get the 2nd element of the first inner array, it'd be `favMovies[2][1]`. – kelsny Oct 25 '22 at 15:39
  • Is it possible to find the index number if there is a large array? – theaminuldev Oct 25 '22 at 15:44
  • Can you add some detail of what you need to do with favMovies? Search if it contains some value, add/remove items, display all favMovies in page etc. – Libor Oct 25 '22 at 15:50
  • I Want to display all favMovies – theaminuldev Oct 25 '22 at 15:56
  • Does this answer your question? [How can I access and process nested objects, arrays, or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – jabaa Oct 25 '22 at 16:03

1 Answers1

1

Use recursive function for find all elements.

Like this:

   const favMovies = [
    'Begin Again', 'Soul',
    ['Matrix', 'Matix Reloaded', 'Matrix Revolutions'],
    ['Frozen', 'Frozen 2',
        ['Tangled', 'Alladin']
    ]
   ];

   function recursive_for(arr){
      for(var key in arr){
         if(arr[key] instanceof Array){
            recursive_for(arr[key]);
         }else{
            console.log(arr[key]);
         }
      }
   }

   recursive_for(favMovies);
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17