• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / JavaScript Arrays / Nested Arrays in JavaScript

Nested Arrays in JavaScript

10 June 2008 / 13 Comments

In previous tutorials we’ve taken a look at JavaScript array basics, manipulating arrays, and sorting arrays. So far, all the arrays we’ve dealt with have been “flat” arrays; each array element contains a single value, such as a number, string, or object.

However, like most programming languages, JavaScript lets you create arrays inside arrays, known as nested arrays. In a nested array, the elements of one array are themselves arrays. For example:


var pets = new Array ( );
pets[0] = new Array ( "Sheba", 13, "cat" );
pets[1] = new Array ( "Jasper", 12, "dog" );
alert ( pets[0][0] + " is a " + pets[0][1] + " year old " + pets[0][2] ); // Displays "Sheba is a 13 year old cat"
alert ( pets[1][0] + " is a " + pets[1][1] + " year old " + pets[1][2] ); // Displays "Jasper is a 12 year old dog"

Here we’ve created an array of 2 elements. Each element is in turn an array containing 3 elements. To access the elements of the inner arrays, you simply use two sets of square brackets. For example, pets[1][2] accesses the 3rd element of the array inside the 2nd element of the pets array.

You can nest arrays as deeply as you like. For example, here we’ve created a top-level array called animals, into which we’ve placed the above pets array, as well as a similar dinosaurs array — that’s 3 levels of nesting in total:


var pets = new Array ( );
pets[0] = new Array ( "Sheba", 13, "cat" );
pets[1] = new Array ( "Jasper", 12, "dog" );
var dinosaurs = new Array ( );
dinosaurs[0] = new Array ( "Cyril", 45, "Tyrannosaur" );
dinosaurs[1] = new Array ( "Gertrude", 72, "Brontosaur" );
var animals = new Array ( pets, dinosaurs );
alert ( animals[0][1][0] + " is a " + animals[0][1][1] + " year old " + animals[0][1][2] ); // Displays "Jasper is a 12 year old dog"
If you’re used to a language like C, you may be wondering if you can create multi-dimensional arrays in JavaScript. While JavaScript doesn’t support true multi-dimensional arrays, you can use array nesting, as described above, to achieve the same effect.

Looping through nested arrays

Of course, once you start nesting arrays you quickly end up with lots of array elements. The easiest way to work with large arrays is to use loops. And in order to process nested arrays, you need to use nested loops.

For example, the following code loops through the animals nested array we created above, displaying each of the animals, along with their ages and types:


for ( i=0; i<animals.length; i++ )
{
  for ( j=0; j<animals[i].length; j++ )
  {
    alert ( animals[i][j][0] + " is a " + animals[i][j][1] + " year old " + animals[i][j][2] );
  }
}

You now know how to create and use nested arrays in JavaScript. You’ll find nested arrays are useful when you want to store highly structured data — such as our animals example above — and when you’re creating multidimensional data structures (commonly used in games and graphics applications). Enjoy!

Filed Under: JavaScript Arrays Tagged With: dimensions, games, graphics, length, looping, loops, multi-dimensional, multidimensional arrays, nesting, three-dimensional, two-dimensional

Reader Interactions

Comments

  1. gummie says

    31 January 2013 at 1:25 pm

    Thank you.

    Reply
    • Isaac says

      19 March 2020 at 11:13 pm

      Mr Matt you only put down the solution for your nested loop.. can u break it down in detail so some of us can really understand and apply .. thanks alot.

      Reply
  2. toni says

    18 April 2019 at 11:56 am

    Hi!

    Imagine something like:

    const newItem = [‘item 1’, ‘item 0’, ‘item 1’, ‘item 2’, ‘item 1’, ‘item 0’];

    If I want to remove all ‘item 1’ I can use:

    for(let i = newItem.length-1; i–;){
    if (newItem[i] === “item 1”) newItem.splice(i, 1);
    }

    The question is if I have an array inside another array how can I do?
    const newItem = [
    [‘item 1’, ‘item 0’, ‘item 1’],
    [‘item 2’, ‘item 1’, ‘item 0’]
    ];

    Thanks

    Reply
    • Matt Doyle says

      29 April 2019 at 11:44 pm

      Nested loops should do the trick. Place a for loop inside another for loop. The outer loop iterates though the items in the outer array; the inner loop iterates through the items in the inner arrays.

      Reply
  3. ProDevs says

    26 February 2020 at 6:55 pm

    @Toni,
    You may want to use nested loop like,

    const newItem = [
      ['item 1', 'item 0', 'item 1'],
      ['item 2', 'item 3', 'item 1']
    ];
    for(let i=0; i<newItem.length; i++){
    	for(let j=0; j<newItem[i].length; j++){
      console.log(newItem[i][j]);
      	if (newItem[i][j] === 'item 1') newItem[i].splice(j, 1);
      }
    }
    console.log(newItem);
    Reply
  4. Quicky says

    15 April 2020 at 11:17 am

    Hi Mat, I got a trick problem.
    I extract from two differen Databases in different environments Data to arrays.
    I merge this two arrays an get a wrong json .
    The content ist there as

    [
    	{
    		"0": "ACT",
    		...	
    	}
    ][
    ]
    

    If I read the result

     success: function(data) {
    			$.each(data,
    				function(counter, daten) {
    Something went wrong !!! getTableDetail [object Object] req = parsererror status = SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 738 of the JSON data err = undefined
    

    Same problem I have when I get the result in TWO Arrays like

    [{"0":"ACT","1":"Tabelle Akten",...}][{"0":"ACT","1":"DB2INST1",...}]
    
    Reply
    • Matt Doyle says

      15 April 2020 at 11:26 am

      Can you post the full code on something like https://codesandbox.io so I can see the problem?

      Reply
      • Quicky says

        16 April 2020 at 6:12 am

        Hi Matt,

        I load a zip with all informatios on my server.
        you can download it here.

        http://dmdg.io/dmdg.zip

        Hope the errordescription gave you all information yo need.

        Kind regards Gert

        Reply
  5. Rupesh patil says

    5 November 2020 at 4:49 pm

    How i can print all the elements array.
    For example:
    Input:
    Let arr= [1,2,[3,4,[5,6,7]]];
    Output : 1234567

    Reply
    • Velusamy says

      30 June 2021 at 4:22 pm

      [1,2,[3,4,[5,6,7]]].flat(Infinity).join(“”); // 1234567

      Reply
  6. muhammad shahroz says

    4 October 2021 at 2:33 pm

    var = arr [[{},{},{}],[{},{},{}],[{},{},{}],[{},{},{}],[{},{},{}],];
    how to access inside of obj name etc

    Reply
  7. Her says

    10 November 2021 at 2:22 pm

    Very helpful. Thank you!

    Reply
  8. Ricardo Leme Silva says

    18 January 2022 at 4:15 am

    I could kiss you!! LOL. A whole day to discover you…

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits