skip to Main Content

I have two arrays – array1 and array2 as shown in the code snippet below. I want to store following information in a message variable such that I could use that in a jQuery dialog.

So, in case of following arrays, I want have my message variable hold following information:

1 . File ABC012345 is located inside BOX#9

2.  File DEF06789 is located inside BOX#10
var array1 = [
  "ABC012345",
  "DEF06789"
]

var array2 = [
  "BOX#9",
  "BOX#10"
]



let messageOne = "1.File "+array1[0]+" is located inside "+array2[0];

let messageTwo = "2.File "+array1[1]+" is located inside "+array2[1];

//console.log(messageOne);

//console.log(messageTwo);

for (i = 0 ; i < array1.length; i++){

   for (j = 0 ; j < array2.length ; j ++) {
   
   let message = "File "+array1[i]+" is located inside "+array2[j];
   console.log(message);
   
   }


}

But the way I’m attempting to do is producing incorrect results. Is there a better / correct way of approachin it?

2

Answers


  1. You don’t need to nested loop for this case, you can do it in just 1 loop

      for (i = 0 ; i < array1.length; i++){
           let message = "File "+array1[i]+" is located inside "+array2[i];
           console.log(message);
      }
    
    Login or Signup to reply.
  2. You do not need nested loops here. Instead, you should use a single loop and index both arrays at the same time.

    Demo:

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    
    <button id="openDialog">Open Dialog</button>
    
    <div id="myDialog" title="File Locations"></div>
    
    <script>
    $(document).ready(function() {
      var array1 = [
        "ABC012345",
        "DEF06789"
      ];
    
      var array2 = [
        "BOX#9",
        "BOX#10"
      ];
    
      let dialogContent = "<ul>"; //start an unordered list
    
      for (let i = 0; i < Math.min(array1.length, array2.length); i++) {
        let message = (i + 1) + ". File " + array1[i] + " is located inside " + array2[i];
        dialogContent += "<li>" + message + "</li>"; //add each message as a list item
      }
    
      dialogContent += "</ul>"; //close the unordered list
    
      //create a button click event to open the dialog
      $("#openDialog").on("click", function() {
        $("#myDialog").html(dialogContent);
        $("#myDialog").dialog({
          modal: true,
          width: 400,
          buttons: {
            "Close": function() {
              $(this).dialog("close");
            }
          }
        });
      });
    });
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search