Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop inside For Loop Javascript

For some reason this statement is skipping some data.Am I missing a continue statement somewhere or something ? Here is the code

for (var i = 0, len = data.ORDER_STATUS[0].ORDERS.length; i < len; i++) {
  if (data.ORDER_STATUS[0].ORDERS[i].SEC_TYPE == "MLEG") {
    for (var i = 0; i < data.ORDER_STATUS[0].ORDERS[i].LEGS.length; i++) {
      LEGS += '<tr class="MLEGS"><td class="orderFirst">' +
        data.ORDER_STATUS[0].ORDERS[i].LEGS[i].SYMBOL +
        '</td><td>' + data.ORDER_STATUS[0].ORDERS[i].LEGS[i].ACTION +
        '</td><td>' + data.ORDER_STATUS[0].ORDERS[i].LEGS[i].QTY +
        '</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
    }
  }
}
like image 242
Bootleg Avatar asked Aug 15 '11 23:08

Bootleg


People also ask

Can we use for loop inside for loop JavaScript?

Javascript supports the nested loop in javascript. The loop can have one or more or simple can have any number of loops defined inside another loop, and also can behave n level of nesting inside the loop. The nested loop is also called as inner loop and the loop in which the nested loop defined is an outer loop.

Can you run two for loops simultaneously in JavaScript?

TL;DR: Yes, in the initializer and loop (not the condition) sections, with commas.

How do you avoid a loop inside a loop?

The complexity of having nested loops in your case is O(n * m) - n the length of orderArr , and m the length of myArr . This solution complexity is O(n + m) because we're creating the dictionary object using Array#reduce with complexity of O(m), and then filtering the orderArray with a complexity of O(n).

What are the 3 parts of a for loop in JavaScript?

JavaScript for loop is used to execute code repeatedly. for loop includes three parts: initialization, condition and iteration.


2 Answers

Use a different variable on the inner loop, like j instead of i.

for (var i = 0, len=data.ORDER_STATUS[0].ORDERS.length; i < len; i++) {
    //...

   for (var j = 0; j < data.ORDER_STATUS[0].ORDERS[i].LEGS.length; j++){
       //...
       data.ORDER_STATUS[0].ORDERS[i].LEGS[j].SYMBOL + 
like image 179
user113716 Avatar answered Oct 05 '22 22:10

user113716


you are using "i" in your outer an inner loops. you need to use a different variable in the inner loop: i have used "inner" below as and example.

for (var i = 0, len=data.ORDER_STATUS[0].ORDERS.length; i < len; i++) {
    if (data.ORDER_STATUS[0].ORDERS[i].SEC_TYPE=="MLEG"){
      for (var inner = 0; inner  < data.ORDER_STATUS[0].ORDERS[i].LEGS.length; inner ++) {
          // do something
      }
    }
  }
like image 38
Dave Avatar answered Oct 06 '22 00:10

Dave