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

This is an array of arrays. It is a little bit easier to read like this:

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

That makes it a little bit easier to see that you have an array of 3 arrays. The outer 'for' will loop through each of 1st level arrays. So the very first outer for loop when i=0 you are going to grab the first inner array [1,2]:

for (var i=0; i < arr.length; i++) {
    //First time through i=0 so arr[i]=[1,2];
}

In the inner loop you are going to loop through each of the 3 inner arrays one at a time.

for (var j=0; j < arr[i].length; j++) {
    //Handle inner array.
}

This argument grabs the length of the inner array:

arr[i].length

So on your first time through the outer loop i=0 and arr[i] is going to equal [1,2] because you are grabbing the 0th element. Remember, arrays elements are always counted starting at 0, not 1.

Finally you are printing out the results with:

console.log(arr[i][j]);

The first time through you can break it down a little. i=0 and j=0. arr[0][0] which translates as grab the first element from the outer array and then the first element from the first inner array. In this case it is '1':

[
    [1,2], <-- 0
    [3,4], <-- 1
    [5,6]  <-- 2
];

The code will loop through the first first set [1,2], then the second [3,4], and so on.

Answer from Gremash on Stack Overflow
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ nesting-for-loops-in-javascript
Nesting For Loops in JavaScript
June 2, 2020 - Because arr is a multi-dimensional array, you'll need two for loops: one to loop through each of the sub-arrays arrays, and another to loop through the elements in each sub-array.
Top answer
1 of 7
21
var arr = [[1,2], [3,4], [5,6]];

This is an array of arrays. It is a little bit easier to read like this:

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

That makes it a little bit easier to see that you have an array of 3 arrays. The outer 'for' will loop through each of 1st level arrays. So the very first outer for loop when i=0 you are going to grab the first inner array [1,2]:

for (var i=0; i < arr.length; i++) {
    //First time through i=0 so arr[i]=[1,2];
}

In the inner loop you are going to loop through each of the 3 inner arrays one at a time.

for (var j=0; j < arr[i].length; j++) {
    //Handle inner array.
}

This argument grabs the length of the inner array:

arr[i].length

So on your first time through the outer loop i=0 and arr[i] is going to equal [1,2] because you are grabbing the 0th element. Remember, arrays elements are always counted starting at 0, not 1.

Finally you are printing out the results with:

console.log(arr[i][j]);

The first time through you can break it down a little. i=0 and j=0. arr[0][0] which translates as grab the first element from the outer array and then the first element from the first inner array. In this case it is '1':

[
    [1,2], <-- 0
    [3,4], <-- 1
    [5,6]  <-- 2
];

The code will loop through the first first set [1,2], then the second [3,4], and so on.

2 of 7
9

The double for loop you have above works like so:

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

 for (var i=0; i < arr.length; i++) {
  // i = 0, then we loop below:
  for (var j=0; j < arr[i].length; j++) {
    //here we loop through the array which is in the main array
    //in the first case, i = 0, j = 1, then we loop again, i = 0, j = 1
    console.log(arr[i][j]);
    //after we finish the stuff in the 'j' loop we go back to the 'i' loop 
    //and here i = 1, then we go down again, i, remains at 1, and j = 0, then j = 1
    //....rinse and repeat, 
  }
}

In plain english:

We grab the first element in the main array, which is an array itself, we loop through that, and log at each index, this is terminated by our length condition in the second loop. We then move to to the next index of the main array, which is an array itself.... and so on, until we reach the end of the main array

To access and index in the main array, we need to use array[i] - that index holds an array - so to go INTO that array, we need to use array[i][j]

Hope that makes sense!

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ nesting-for-loops-in-javascript
Nesting For Loops in JavaScript - GeeksforGeeks
In JavaScript, you can nest different types of loops to achieve the desired iteration. Common types include a For Loop within another For Loop, which is a standard nested loop for iterating over multi-dimensional arrays.
Published ย  August 5, 2025
๐ŸŒ
LambdaTest Community
community.lambdatest.com โ€บ general discussions
Understanding Nested For Loops in JavaScript Arrays - LambdaTest Community
October 24, 2024 - Iโ€™m currently learning JavaScript on FreeCodeCamp, and I encountered an example involving nested for loops in JavaScript in one of their exercises: var arr = [[1, 2], [3, 4], [5, 6]]; for (var i = 0; i < arr.length; i++โ€ฆ
Top answer
1 of 5
5

As others have already mentioned, Array.prototype.filter() might be the simplest approach (or Array.prototype.reduce() could also be used but would require more conditional logic). It would typically be slower than the nested for loops because it would be adding additional function calls, but for small data sets it typically wouldn't be noticeable. For example, I did a search on Google for "jsperf filter nested loop" and found this jsPerf test.

Using Array.prototype.filter() on A2, pass a callback function that returns true when the value at property value is included in A1 by checking A1.indexOf() for a value greater than -1.

const result = A2.filter(function(o) {
    return A1.indexOf(o.value) > -1;
});

This can be simplified to a single line using an ES-6 arrow function and Array.prototype.includes() (Not supported by IE):

const result = A2.filter(o => A1.includes(o.value));

Try it in this snippet:

var A1  = ["1","2","3","4"];

var A2 = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
    {label:"five", value:"5"},
    {label:"six", value:"6"},
];
const result = A2.filter(o => A1.includes(o.value));
console.log('result', result);


If you wanted to use Underscore.js, _.filter() and _.includes() could be used to filter out any object in A2 without a value for the value property contained in A1. Expand the snippet below for a demonstration.

var A1  = ["1","2","3","4"];

var A2 = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
    {label:"five", value:"5"},
    {label:"six", value:"6"},
];
const result = _.filter(A2, function(o) { return _.includes(A1, o.value);});
console.log('result', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

There is an Underscore helper _.pluck() but that is used to collect a value from each item in a collection at a given property (similar to Array.prototype.map().

Lodash also has the same helpers: _.filter() and _.includes().

var A1  = ["1","2","3","4"];

var A2 = [
    {label:"one", value:"1"},
    {label:"two", value:"2"},
    {label:"three", value:"3"},
    {label:"four", value:"4"},
    {label:"five", value:"5"},
    {label:"six", value:"6"},
];
const result = _.filter(A2, function(o) { return _.includes(A1, o.value);});
console.log('result', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Though some question whether libraries like lodash and underscore are really needed anymore. For a discussion on that, check out this article.

2 of 5
5

You can use some built in functions instead of the for loops.

var result = A2.filter(e => A1.includes(e.value));

I can't say if this is much faster, since those functions still loop through the arrays. You'll have to time this with some large input to test.

Be aware that Internet Explorer doesn't support .includes or arrow functions. IE friendly version:

var result = A2.filter(function(e) {return A1.indexOf(e.value) !== -1});
๐ŸŒ
Codedamn
codedamn.com โ€บ news โ€บ javascript
Nested for loops in JavaScript: Why?
January 4, 2023 - With the help of a nested for loop, we can directly access the elements of an array, unlike other nested loops.
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_for.asp
JavaScript for Statement
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
Find elsewhere
๐ŸŒ
sebhastian
sebhastian.com โ€บ nested-loops-javascript
JavaScript nested loops explained | sebhastian
March 24, 2021 - If you want to log each of the elements inside the nested arrays, you need to iterate through the nested arrays by using arr[i].length for the condition of the loop:
๐ŸŒ
Mozilla
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Guide โ€บ Loops_and_iteration
Loops and iteration - JavaScript - MDN Web Docs - Mozilla
The for...of statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javascript โ€บ javascript_nested_loop.htm
JavaScript - Nested Loop
In the following code snippet that demonstrates how we can use nested for loops. let rows = [1, 2, 3]; let columns = [4, 5, 6]; for (let i = 0; i < rows.length; i++) { for (let j = 0; j < columns.length; j++) { console.log(rows[i] + " " + columns[j]); } } ... We have two arrays, one is an array ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-use-nested-for-loop-in-javascript
How to use nested for loop in JavaScript?
November 10, 2022 - We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the name suggests, is made up of more than one for loop one nested inside of the other. This allows
Top answer
1 of 2
3

The structure you're using should be more like this:

var data = [

    {title:'Row Title 1', contents: [

      {leftCol:'Some text for left column',rightCol:'Some text for right column'},
      {leftCol:'Some text for left column',rightCol:'Some text for right column'},
      {leftCol:'Some text for left column',rightCol:'Some text for right column'}

    ],

    // ...
];

That way, each row is an object with a "title" attribute and a "contents" attribute. Your loop would then look like this:

for (var i=0, j=data.length; i < j; i++) {

    if(data[i].title != null){
        document.write('<b>'+data[i].title+'</b><br />');
    }

    for(var p=0, plen=data[i].contents.length; p < plen; p++){
        document.write('<p style="background:#eee;">'+data[i].contents[p].leftCol+'</p>');
        document.write('<p>'+data[i].contents[p].rightCol+'</p>');       
    }
}
2 of 2
1

If you want to make your code more robust follow these guidelines:

  1. It's always better to initialize for loops like so if you have a length: for (var i = 0, l = length; l--; i++). The reason for this syntax is explained in fuller detail by Nicholas C. Zakas.
  2. Always store variables accessed multiple times in a local variable. It speeds up execution (e.g. idata = data[i];).
  3. Avoid duck typing as far as possible (e.g. data[i].title != null). Check for the type of the variable first. It's slower, but the code is easier to understand and maintain. Try the typeOf function at the bottom of the post (e.g. typeOf(idata) === "Object").
  4. It's usually always better to use === instead of == and !== instead of != because they don't perform type coercion which might lead to unexpected results.
  5. Instead of creating multiple inline styles, create a single class .greyBackground { background-color: #EEEEEE; } and set the className of each leftCol paragraph to greyBackground.
  6. Avoid using document.write. It's slow, causes reflow of the document, and halts loading assets while the page is downloading. The best way to create dynamic content using JavaScript is to use the document.createDocumentFragment method as I'll explain below.
  7. It's always better to create nodes in JavaScript yourself. If you use a string in document.write or element.innerHTML then the browser parses the string and converts it into the nodes anyway. Thus using that method is slower.

This is how I would have written your JavaScript:

var data = [
    "Row Title 1",
    {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    },
    "Row Title 2",
    {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }, {
        "leftCol": "Some text for left column",
        "rightCol": "Some text for right column"
    }
];

function typeOf(value) {
    if (value === null) {
        return "null";
    } else if (typeof value === "undefined") {
        return "undefined";
    } else {
        return Object.prototype.toString.call(value).slice(8, -1);
    }
}

var element;
var fragment = document.createDocumentFragment();
var idata;

for (var i = 0, l = data.length; l--; i++) {
    idata = data[i];
    if (typeOf(idata) === "Object") {
        element = document.createElement("p");
        element.className = "greyBackground";
        element.appendChild(document.createTextNode(idata.leftCol));
        fragment.appendChild(element);

        element = document.createElement("p");
        element.appendChild(document.createTextNode(idata.rightCol));
        fragment.appendChild(element);
    } else {
        element = document.createElement("b");
        element.appendChild(document.createTextNode(idata));
        fragment.appendChild(element);

        element = document.createElement("br");
        fragment.appendChild(element);
    }
}

document.body.appendChild(fragment);

Test my page and yours. In all probability mine will execute faster. If you have any doubts feel free to ask me. Cheers! =)

๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ javascript
Accessing nested arrays using the for loop - JavaScript - The freeCodeCamp Forum
July 2, 2022 - Tell us whatโ€™s happening: Describe your issue in detail here. Issue - I donโ€™t understand how the for loops accesses each sub-element within this problem below. I know how it accesses the first sub-element of the first element of array arr, but how does it access the second sub-element of ...
๐ŸŒ
Kodeclik
kodeclik.com โ€บ nested-loops-javascript
Nested Loops in Javascript
October 16, 2024 - This code implements the bubble sort algorithm, which employs nested for loops to compare and swap elements in the array until it is sorted in ascending order.
๐ŸŒ
Programiz PRO
programiz.pro โ€บ resources โ€บ js-nested-loop
Understanding Nested Loops in JavaScript
If we want to print all possible combinations, we can use nested loops. // List of car attributes let attributes = ["Electric", "Fast"]; let cars = ["Tesla", "Porsche"]; for (let attribute of attributes) { for (let car of cars) { console.log(attribute, car); } } ... The outer loop iterates through the attributes array.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 249739 โ€บ nested-for-loops-in-js
Nested for loops in JS | Sololearn: Learn to code for FREE!
Thank you: var arr = [[1,2], [3,4], [5,6]];: for (var i=0; i < arr.length; i++) { for (var j=0; j < arr[i].length; j++) { console.log(arr[i][j]); } } ... It will start from the outer or top loop, looping 3 times as there are 3 arrays.
๐ŸŒ
DEV Community
dev.to โ€บ ddrummer3993 โ€บ nested-object-iteration-using-multiple-forin-loops-4k6l
Nested object iteration using multiple for...in Loops. - DEV Community
March 23, 2022 - Object.entries(objName) //=> returns an array of property arrays. Use a for...in loop to iterate over all keys. For this example we will be using multiple for...in loops to dive down into our nested objects, however for anyone learning about objects I HIGHLY recommend you look up the mdn on the first two examples listed above.
๐ŸŒ
Softuni
js-book.softuni.org โ€บ chapter-06-nested-loops.html
6.1. Nested Loops ยท Programming Basics with JavaScript
Here is an example that illustrates nested loops. The aim is again to print a rectangle made of n *_ _n stars, in which for each row a loop iterates from 1 to n, and for each column a nested loop is executed from 1 to *n: